Tkinter 16 – Binding and Frames

Binding


Binding is what you do to link an action to the user to a code that makes something. In this example (from Effbot, with some changes), we see how to print the coordinates of the mouse pointer when the user clicks on the Frame.

  1. import tkinter as tk
  2. root = tk.Tk()
  3. def clicked(event):
  4.     label[‘text’] = event.x, event.y
  5. frame = tk.Frame(root, width=100, height=100)
  6. frame[“bg”] = “yellow”
  7. frame.bind(“<Button-1>”, clicked)
  8. frame.pack()
  9. label = tk.Label(root)
  10. label.pack()
  11. root.mainloop()

A little game with Frame and binding

In the following code I made some changes to create a little game where you have to find a secret spot. When you are close the Frame becomes orange, when you hit the spot it becomes red.

  1. import tkinter as tk
  2. import random
  3. root = tk.Tk()
  4. def clicked(event):
  5.     label[‘text’] = event.x, event.y
  6.     if event.x in range(x 10, x 10) and event.y in range(y 10, y 10):
  7.         label[‘text’] = “YOU WIN!”
  8.         label[‘bg’] = “yellow”
  9.         frame[‘bg’] = “red”
  10.     elif event.x in range(x 30, x 30) and event.y in range(y 30, y 30):
  11.         label[‘text’] = “You’re close”
  12.         label[‘bg’] = “yellow”
  13.         frame[‘bg’] = “orange”
  14.     else:
  15.         frame[‘bg’] = “yellow”
  16. x = random.randint(1, 99)
  17. y = random.randint(1, 99)
  18. frame = tk.Frame(root, width=100, height=100)
  19. frame[“bg”] = “yellow”
  20. frame.bind(“<Button-1>”, clicked)
  21. frame.pack()
  22. label = tk.Label(root)
  23. label.pack()

The game in action

In this video you can see what’s the game like. It’s a very basic example to test the use of binding.

Tkinter – Secret spot game explained

Tkinter – An example of an App

 

Tkinter – Example 2: a calculator

 

Tkinter 16 – Binding and Frames

 

Tkinter p. 6 – A quiz with just labels

 

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.