Master Tkinter: Frames, Dialogs, Treeviews, and Event Handling in Python

This article walks through advanced Tkinter techniques, covering frame creation, various dialog boxes, treeview widgets, color selection, layout managers, and comprehensive mouse and keyboard event binding, providing ready-to-use code snippets for building robust Python GUIs.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Tkinter: Frames, Dialogs, Treeviews, and Event Handling in Python

Continuing from the previous tutorial on Tkinter installation, basic widgets, dropdown menus, and canvas, this article delves deeper into Tkinter's GUI components.

10. Frame

A frame creates a sub‑window within the main window, useful for multiple window interactions such as chat or games.

fm = tk.Frame(root)  # create a frame on root
fm.pack()            # add it to the layout
# create two frames inside the frame
f1 = tk.Frame(fm)
f2 = tk.Frame(fm)
# add widgets with different colors for distinction
f1.pack()
f2.pack()

tk.Label(f1, text='标签一', bg='green').pack()
tk.Button(f1, text='按钮一', bg='green').pack()
tk.Label(f2, text='标签二', bg='red').pack()
tk.Button(f2, text='按钮二', bg='red').pack()

The frame acts as a parent window containing two child frames, each holding two widgets, which is handy for organizing complex interfaces.

11. Dialogs and Input

1. messagebox

Import the messagebox module to display various pop‑up dialogs.

from tkinter import messagebox

1. Information

messagebox.showinfo(title='提示', message='你需要这么做')

2. Warning

messagebox.showwarning(title='警告', message='你不能这么做')

3. Error

messagebox.showerror(title='错误', message='你做错了')

4. Ask Question

messagebox.askquestion(title='选择', message='你是否这样做')

5. OK/Cancel

messagebox.askokcancel(title='选择', message='你是否这样做')

6. Yes/No

messagebox.askyesno(title='选择', message='你是否这样做')

7. Retry/Cancel

messagebox.askretrycancel(title='选择', message='你是否这样做')

The underlying _show function accepts parameters such as default, icon, message, parent, title, and type.

2. simpledialog

Use simpledialog for interactive input dialogs. from tkinter import simpledialog Example of an integer input dialog:

simpledialog.askinteger(title='显示', prompt='输入', initialvalue='12')

12. File Dialogs

Import filedialog to open or save files and directories.

from tkinter import filedialog

1. Open file name

filedialog.askopenfilename()

2. Open file object

filedialog.askopenfile()

3. Open multiple file objects

filedialog.askopenfiles()

4. Open multiple file names

filedialog.askopenfilenames()

5. Choose directory

filedialog.askdirectory()

6. Save as file object

filedialog.asksaveasfile()

7. Save as file name

filedialog.asksaveasfilename()

8. Custom load dialog

filedialog.LoadFileDialog(root).go()

9. Custom save dialog

filedialog.SaveFileDialog(root).go()

13. Treeview List

The treeview widget displays hierarchical data similar to a file system.

from tkinter import ttk
t = ttk.Treeview(root)  # load tree widget
t.pack()
n = t.insert('', 0, text="hello", values=("1"))
n1 = t.insert(n, 1, text="cq", values=("2"))
n2 = t.insert(n, 1, text="sc", values=("2"))
t.insert(n1, 2, text='fd', values=("3"))
t.insert(n1, 2, text='we', values=("3"))
t.insert(n2, 2, text='1', values=("3"))
t.insert(n2, 2, text='2', values=("3"))

This approach allows dynamic construction of large hierarchical structures such as directory trees.

14. Color Chooser

Use colorchooser to let users pick colors.

from tkinter import colorchooser
colorchooser.askcolor()

15. Widget Layout

Tkinter provides three geometry managers: pack, grid, and place.

1. pack

tk.Label(root, text='1').pack(side='top')   # top
tk.Label(root, text='2').pack(side='bottom')# bottom
tk.Label(root, text='3').pack(side='left')  # left
tk.Label(root, text='4').pack(side='right') # right

Pack can also control fill behavior:

tk.Label(root, text='1').pack(fill='y')   # vertical fill
tk.Label(root, text='2').pack(fill='x')   # horizontal fill
tk.Label(root, text='3').pack(fill='both')# both directions
tk.Label(root, text='4').pack(fill='none')# no fill

2. grid

tk.Label(root, text='1').grid(row=3, column=3)  # place at row 3, column 3

Grid also supports spanning and padding:

tk.Label(root, text='1').grid(row=3, column=3, rowspan=3, ipadx=6)
tk.Label(root, text='2').grid(row=4, column=4, columnspan=3, pady=8)

3. place

tk.Label(root, text='43').place(x=100, y=200, width=10, height=5)  # absolute positioning

16. Mouse and Keyboard Events

Binding events to widgets adds interactivity. Common binding functions include bind, bind_class, and bind_all. Example event signatures:

bind(sequence, func, add)
bind_class(className, sequence, func, add)
bind_all(sequence, func, add)

Typical mouse events: <Button-1> (left click), <ButtonRelease-1>, <B1-Motion>, <Double-Button-1>, <Enter>, <Leave>, <MouseWheel>. Keyboard events: <KeyPress-A>, <Alt-KeyPress-A>, <Double-KeyPress-A>, <Lock-KeyPress-A>. Window events include Activate, Configure, Destroy, FocusIn, FocusOut, etc. The event object provides attributes such as char, keycode, keysym, x, y, and widget for handling logic.

These sections together cover the essential Tkinter components and techniques needed to build functional Python GUIs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Widgetsevent bindingDialog
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.