[newbie] problem trying out simple non object oriented use of Tkinter

Christian Gollwitzer auriocus at gmx.de
Fri Dec 6 13:03:19 EST 2013


Am 06.12.13 14:12, schrieb Jean Dubois:
> It works but it's not all clear to me. Can you tell me what "label.bind("<1>", quit)" is standing for? What's the <1> meaning?

"bind" connects events sent to the label with a handler. The <1> is the 
event description; in this case, it means a click with the left mouse 
button. The mouse buttons are numbered 1,2,3 for left,middle,right, 
respectively (with right and middle switched on OSX, confusingly). It is 
actually short for

<Button-1>


Binding to the key "1" would look like this

<Key-1>

The event syntax is rather complex, for example it is possible to add 
modifiers to bind to a Shift-key + right click like this

<Shift-3>

It is described in detail at the bind man page of Tk.

http://www.tcl.tk/man/tcl8.6/TkCmd/bind.htm

The event object passed to the handler contains additional information, 
for instance the position of the mouse pointer on the screen.

In practice, for large parts of the interface you do not mess with the 
keyboard and mouse events directly, but use the corresponding widgets.
In your program, the label works as a simple pushbutton, and therefore a 
button should be used.

#!/usr/bin/env python
import Tkinter as tk
import ttk # for modern widgets
import sys

# no underscore - nothing gets passed
def quit():
     sys.exit()

root = tk.Tk()
button = ttk.Button(root, text="Click mouse here to quit", command=quit)
button.pack()
root.mainloop()


note, that

1) nothing gets passed, so we could have left out changing quit(). This 
is because a button comand usually does not care about details of the 
mouse click. It just reacts as the user expects.

2) I use ttk widgets, which provide native look&feel. If possible, use 
those. Good examples on ttk usage are shown at 
http://www.tkdocs.com/tutorial/index.html

HTH,
	Christia



More information about the Python-list mailing list