Use ttk.button() etc. whenever possible. That's because ttk is the newest version. tk.button() and others are old, don't use them unless ttk. doesn't work.
For example, you may wish to bind a key to a button. This helps you streamline the control of an application. If you just have two input methods there could be a problem with things like arrows and backspace or delete messing up the calculator window.
import tkinter as tk from tkinter import ttk def press_eq(event): print('Equals key pressed.') root = tk.Tk() button1 = ttk.Button(root, text='=') button1.bind('<KeyPress-Return>', press_eq) button1.focus() button1.pack(expand=True) root.mainloop()
Observe carefully that <Button> and <Button-1> events are both the same event, but one has a specifier. Events such as <KeyPress> and <KeyPress-Enter> are discussed on some sites such as https://www.pythontutorial.net/tkinter/tkinter-event-binding/.
import tkinter root = tkinter.Tk() def right_click_handler(event): # event.num == 2 is MOUSE. if event.num == 2: print("RIGHT CLICK") root.bind("<Button-1>", lambda x: print("LEFT CLICK")) root.bind("<Button>", right_click_handler) root.mainloop()
Here, a lambda is used to handle left clicks with <Button-1> while the more general <Button> handles both left and right, but uses
event.num == 2
to determine right click vs. left click, so it could handle both if needed.
To capture a click-and-drag event use any of the <B1-Motion> (left-click), <B2-Motion> (right click) or <B3-Motion> (middle mouse button click). Note that Note that when dragging outside of an element the event still fires.
import tkinter root = tkinter.Tk() label = tkinter.Label(root, text="HEY") label.pack() def drag_handler(event): print(event.x, event.y) label.bind("<B1-Motion>", drag_handler) root.mainloop()
Hovering over an element sends out two events in sequence, <Enter> and <Leave>
import tkinter root = tkinter.Tk() label = tkinter.Label(root, text="HELLO", bg="white", fg="navy") label.bind("<Enter>", lambda event: event.widget.config(bg="navy", fg="white")) label.bind("<Leave>", lambda event: event.widget.config(bg="white", fg="navy")) label.pack() root.mainloop()