Checkbutton 和 Radiobutton 的使用

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()

效果演示如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咬尾巴的猫在coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值