Mastering Tkinter: Build Interactive Python GUIs with Widgets and Menus
This article provides a comprehensive guide to Python's built‑in Tkinter GUI library, covering installation, window creation, core widgets such as labels, buttons, text boxes, menus, canvases, and advanced features like event binding and layout management, enabling readers to build functional desktop applications.
When writing code, a graphical user interface (GUI) adds a visual layer that makes programs more intuitive. Python includes the Tkinter module for creating GUIs, and this guide walks through its most useful components.
1. Installation and Import
Tkinter is bundled with Python, so no installation is required; simply import it.
<span>import tkinter as tk # alias for brevity</span>2. Instantiate Window
<span>root = tk.Tk() # main window</span>
<span>root.title('hello') # window title</span>
<span>root.geometry('400x500') # size</span>
<span>root.wm_minsize(140, 170) # minimum size</span>
<span>root.wm_maxsize(1440, 2800) # maximum size</span>
<span>root.iconbitmap('1.ico') # window icon (ICO format)</span>
<span>root.resizable(width=False, height=True) # width fixed, height resizable</span>
<span>root.mainloop() # start event loop</span>The first window appears, and many additional methods are available, such as root.quit(), root.destroy(), root.update(), root.wm_title(), and root.configure(background='blue').
3. Basic Widgets
Tkinter provides a rich set of widgets, including labels, buttons, entry fields, list boxes, checkboxes, radio buttons, scales, scrollbars, canvases, and menus.
1. Label
Labels display static text or images. Example:
<span>label = tk.Label(root,
text='Hello',
bg='red',
font=('Arial', 20),
width=10,
height=5)
label.pack() # add to window</span>Label attributes include anchor, background, foreground, borderwidth, width, height, bitmap, font, image, justify, text, textvariable, etc.
2. Button
Buttons trigger actions. Example:
<span>button = tk.Button(root, text='Click Me', command=lambda: label.configure(text='Clicked'))
button.pack()</span>Common button options are anchor, background, bitmap, borderwidth, command, cursor, font, foreground, height, image, state, text, width, padx, pady, activeforeground, textvariable, etc.
3. Entry (Single‑line) and Text (Multi‑line) Widgets
Entry fields accept user input, often used for login forms. Example:
<span>e1 = tk.Entry(root)
e1.pack()
e1.insert(0, 'default text')</span>Multi‑line Text widgets display or edit larger blocks of text.
<span>tt = tk.Text(root, width=40, height=10)
tt.pack()
tt.insert('1.0', 'First line')
tt.delete('1.0', tk.END) # clear all</span>Additional methods include tt.update(), tt.edit_undo(), tt.editredo(), tt.tag_add(), tt.tag_config(), and tt.tag_bind() for styling and event handling.
Remember‑Password Feature
By storing a flag in a StringVar, the entry can toggle between normal and password display.
PhotoImage Viewer
Tkinter’s PhotoImage supports GIF images and can be displayed on a canvas.
4. RadioButton and Checkbutton
These widgets allow single or multiple selections.
<span>rb = tk.Radiobutton(root, text='Option 1', variable=var, value=1)
cb = tk.Checkbutton(root, text='Agree', variable=agree_var)
rb.pack()
cb.pack()</span>Key options include anchor, background, foreground, borderwidth, width, height, bitmap, image, font, justify, text, value, variable, indicatoron, and textvariable.
5. Listbox
Listboxes present a list of selectable items.
<span>lb = tk.Listbox(root)
for item in ['A', 'B', 'C']:
lb.insert(tk.END, item)
lb.pack()</span>6. Scale and Scrollbar
Scales (sliders) adjust numeric values; scrollbars attach to other widgets such as listboxes or text areas.
<span>scale = tk.Scale(root, from=0, to=100, orient=tk.HORIZONTAL)
scale.pack()
sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT, fill=tk.Y)
text = tk.Text(root, yscrollcommand=sb.set)
text.pack()
sb.config(command=text.yview)</span>7. Canvas
Canvas provides drawing capabilities for shapes, images, and custom widgets.
<span># create a blue canvas</span>
canvas = tk.Canvas(root, bg='blue', width=200, height=100)
canvas.pack()
<span># rectangle</span>
canvas.create_rectangle(50, 50, 150, 80, fill='green', outline='red', width=2)
<span># arc</span>
canvas.create_arc(50, 100, 140, 200, style='pieslice', start=0, extent=180)
<span># line with arrow</span>
canvas.create_line(100, 100, 200, 200, arrow='first', arrowshape='30 20 10')
<span># oval</span>
canvas.create_oval(50, 100, 140, 200, fill='red')
<span># polygon (triangle)</span>
canvas.create_polygon(150,150,150,200,70,200, fill='red')
<span># text</span>
canvas.create_text(10,10, text='Hello Text', anchor='w')
<span># bitmap</span>
canvas.create_bitmap(40,40, bitmap='error')
<span># gif image</span>
img = tk.PhotoImage(file='1.gif')
canvas.create_image(10,10, anchor='nw', image=img)
<span># embed a button</span>
bt = tk.Button(canvas, text='hello')
canvas.create_window(100,100, window=bt, anchor='w')8. Combobox (Dropdown List)
The ttk Combobox provides a read‑only dropdown.
<span>from tkinter import ttk
def on_select(event):
print(cb.get())
cb = ttk.Combobox(root, width=12, state='readonly')
cb['values'] = ('请选择-----', '1', '2', '3', '4')
cb.current(0)
cb.bind('<<ComboboxSelected>>', on_select)
cb.pack()</span>9. Menus
Menus organize commands and can appear as dropdowns, right‑click pop‑ups, menubuttons, or option menus.
Dropdown Menu
<span>m = tk.Menu(root)
file = tk.Menu(m, tearoff=False)
m.add_cascade(label='文件', menu=file)
file.add_command(label='新建', accelerator='Ctrl+N')
file.add_command(label='打开', accelerator='Ctrl+O')
file.add_command(label='保存', accelerator='Ctrl+S')
file.add_separator()
file.add_command(label='退出', command=root.quit, accelerator='Ctrl+Q')
edit = tk.Menu(m, tearoff=False)
m.add_cascade(label='编辑', menu=edit)
edit.add_command(label='剪切', accelerator='Ctrl+X')
edit.add_command(label='复制', accelerator='Ctrl+C')
edit.add_command(label='粘贴', accelerator='Ctrl+V')
root.config(menu=m)</span>Right‑Click Popup Menu
<span>def popup(event):
m.post(event.x_root, event.y_root)
root.bind('<Button-3>', popup)</span>Menubutton
<span>def show():
print('hello')
mb = tk.Menubutton(root, text='python', relief=tk.RAISED)
mb.pack()
file = tk.Menu(mb, tearoff=0)
file.add_checkbutton(label='打开', command=show)
file.add_command(label='保存', command=show)
file.add_separator()
file.add_command(label='退出', command=root.quit)
mb.configure(menu=file)</span>OptionMenu
<span>var = tk.StringVar()
var.set('编程语言')
opt = tk.OptionMenu(root, var, 'python', 'php', 'c#', 'c++')
opt.pack()</span>The article emphasizes that Tkinter’s extensive widget set enables developers to create functional desktop applications with custom layouts, event handling, and visual components.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
