首页 > 解决方案 > 选中另一个复选框时取消选中

问题描述

所以问题出在if功能上,它不起作用。它完全忽略了所有值的变化,根本不改变任何值。这段代码有什么问题?

import tkinter as tk
root = tk.Tk()

CheckVar4 = tk.IntVar()
CheckVar5 = tk.IntVar()

C4 = tk.Checkbutton(root, text = "Medium terms", variable = CheckVar4, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 12)

C5 = tk.Checkbutton(root, text = "Hard terms", variable = CheckVar5, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 8)

if CheckVar4.get() == 1:
    CheckVar5.set(0)

if CheckVar5.get() == 1:
    CheckVar4.set(0)

root.mainloop()

标签: pythontkinter

解决方案


也许想改用单选按钮?示例如下

import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

tk.Label(root, 
        text="""Choose a 
programming language:""",
        justify = tk.LEFT,
        padx = 20).pack()
tk.Radiobutton(root, 
              text="Python",
              padx = 20, 
              variable=v, 
              value=1).pack(anchor=tk.W)
tk.Radiobutton(root, 
              text="Perl",
              padx = 20, 
              variable=v, 
              value=2).pack(anchor=tk.W)

root.mainloop()

推荐阅读