tkinter的Checkbutton
和 Radiobutton
是 tkinter
提供的两个常用的按钮小组件。Checkbutton
为复选按钮,允许用户选择多个选项;Radiobutton为单选按钮,各
选项是互斥的。
一、Checkbutton 选项详解
text
: 按钮显示的文本variable
: 关联的变量,用于保存按钮状态command
: 状态改变时调用的函数onvalue
: 按钮选中时变量的值(默认1
)offvalue
: 按钮取消选中时变量的值(默认0
)
二、Radiobutton 选项详解
text
: 按钮显示的文本variable
: 关联的变量,所有Radiobutton
共享同一个变量value
: 当前按钮代表的值,当按钮选中时,变量设置为此值command
: 状态改变时调用的函数
三、示例代码
from tkinter import *
def display_selection():
languages_selected = []
if var_python.get() == 1:
languages_selected.append("Python")
if var_java.get() == 1:
languages_selected.append("Java")
if var_cpp.get() == 1:
languages_selected.append("C++")
os_selected = var_os.get()
result.set(f"Languages: {', '.join(languages_selected)}\nOS: {os_selected}")
root = Tk()
root.title("Checkbutton & Radiobutton Example")
root.geometry("500x300+400+300")
# Checkbutton 部分
Label(root, text="Select Languages:").pack(anchor=W)
var_python = IntVar()
var_java = IntVar()
var_cpp = IntVar()
checkbutton_python = Checkbutton(root, text="Python", variable=var_python, command=display_selection)
checkbutton_java = Checkbutton(root, text="Java", variable=var_java, command=display_selection)
checkbutton_cpp = Checkbutton(root, text="C++", variable=var_cpp, command=display_selection)
checkbutton_python.pack(anchor=W)
checkbutton_java.pack(anchor=W)
checkbutton_cpp.pack(anchor=W)
# Radiobutton 部分
Label(root, text="Select Operating System:").pack(anchor=W)
var_os = StringVar(value="Windows")
radiobutton_windows = Radiobutton(root, text="Windows", variable=var_os, value="Windows", command=display_selection)
radiobutton_linux = Radiobutton(root, text="Linux", variable=var_os, value="Linux", command=display_selection)
radiobutton_mac = Radiobutton(root, text="Mac OS", variable=var_os, value="Mac OS", command=display_selection)
radiobutton_windows.pack(anchor=W)
radiobutton_linux.pack(anchor=W)
radiobutton_mac.pack(anchor=W)
# 显示选择结果
result = StringVar()
Label(root, textvariable=result).pack()
root.mainloop()
效果演示如下: