tkinter 是Python自带的GUI模块,相对于 Pyqt5 等其他界面模块,简单快捷;如对界面美观无需求,直接使用 tkinter 模块即可
本文介绍基本的widgets,源代码来自 《Python GUI Programming》
效果图:
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
root = tk.Tk()
root.title('Python GUI') # 设置窗口标题
root.resizable(0, 0) # 禁止调整窗口大小
# Label 标签
label_a = tk.Label(root, text='Enter a name: ')
label_a.grid(row=0, column=0)
label_b = tk.Label(root, text='Enter a number:')
label_b.grid(row=0, column=1)
# button's recall 按键函数要在按键前实现
def click_me():
button_hello.configure(text='Hello ' + name.get() + number.get())
# button 按键
button_hello = tk.Button(root, text='Click Me!', command=click_me)
button_hello.grid(row=1, column=2)
# Entry 入口
name = tk.StringVar() # 理解为一个容器,下面用 text variable 绑定
name_entered = tk.Entry(root, textvariable=name)
name_entered.grid(row=1, column=0)
name_entered.focus() # 使程序运行后,焦点在这
# Combobox 组合框
number = tk.StringVar()
number_chosen = ttk.Combobox(
root,
textvariable=number,
state='readonly') # readOnly 只读
number_chosen['values'] = (1, 2, 3, 4)
number_chosen.current(0) # current 当前显示的值,0为index,因此显示1
number_chosen.grid(row=1, column=1)
# Checkbutton 检查按钮
checkbutton_disable_value = tk.IntVar()
checkbutton_disable = tk.Checkbutton(
root,
text='Disable',
variable=checkbutton_disable_value,
state='disable') # disable表示不可选
checkbutton_disable.select() # 表示被选择
checkbutton_disable.grid(row=2, column=0, sticky=tk.W) # 居左对齐 West
checkbutton_uncheck_value = tk.IntVar()
checkbutton_uncheck = tk.Checkbutton(
root, text='UnChecked', variable=checkbutton_uncheck_value)
checkbutton_uncheck.deselect() # 不被选择
checkbutton_uncheck.grid(row=2, column=1, sticky=tk.W)
checkbutton_enable_value = tk.IntVar()
checkbutton_enable = tk.Checkbutton(
root, text='Enable',
variable=checkbutton_enable_value)
checkbutton_enable.select()
checkbutton_enable.grid(row=2, column=2, sticky=tk.W)
# Radiobutton 单选框实例
color_blue = 'Blue'
color_gold = 'Gold'
color_red = 'Red'
def radio_call():
radio_value = radioVar.get()
if radio_value == 1:
root.configure(background=color_blue)
if radio_value == 2:
root.configure(background=color_gold)
if radio_value == 3:
root.configure(background=color_red)
radioVar = tk.IntVar()
radio_color_blue = tk.Radiobutton(
root,
text=color_blue,
variable=radioVar,
value=1,
command=radio_call)
radio_color_gold = tk.Radiobutton(
root,
text=color_gold,
variable=radioVar,
value=2,
command=radio_call)
radio_color_red = tk.Radiobutton(
root,
text=color_red,
variable=radioVar,
value=3,
command=radio_call)
radio_color_blue.grid(row=3, column=0, sticky=tk.W)
radio_color_gold.grid(row=3, column=1, sticky=tk.W)
radio_color_red.grid(row=3, column=2, sticky=tk.W)
# ScrolledText 滚动条
scroll_width = 40
scroll_height = 4
scroll = scrolledtext.ScrolledText(
root,
width=scroll_width,
height=scroll_height,
wrap=tk.WORD) # 换行以完整的word为标准,不能写全则换行
scroll.grid(column=0, columnspan=3)
root.mainloop()