如何使Checkbutton的变量起作用并在屏幕上显示一些按钮?

时间:2019-04-17 13:44:29

标签: tkinter pydroid

from Tkinter import *
window = Tk()
CheckVar1 = IntVar()
cbttn = Checkbutton(text="Caps?", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
cbttn.grid(row=3, column=0)
while True:
    if CheckVar1 == 0:
        a = Button(text="a").grid(column=1)
        b = Button(text="b").grid(column=1)
        c = Button(text="c").grid(column=1)
        d = Button(text="d").grid(column=1)
        e = Button(text="e").grid(column=1)
        f = Button(text="f").grid(column=1)
        g = Button(text="g").grid(column=1)
    if CheckVar1 == 1:
        A = Button(text="A").grid(column=1)
    window.mainloop()#makes everything work

我想找出如何根据CheckVar1的值显示不同的按钮。 我没有错误,但是我要使用的代码是if CheckVar1 == 0:if CheckVar1 == 1

1 个答案:

答案 0 :(得分:1)

trace上使用IntVar方法。

from Tkinter import *
window = Tk()
CheckVar1 = IntVar()
cbttn = Checkbutton(text="Caps?", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5,width = 20)
cbttn.grid(row=3, column=0)

def trace_method(*args):
    print ("Changed")
    if CheckVar1.get() == 0: #note that you need to call `get` method on the IntVar
        a = Button(text="a").grid(column=1)
        b = Button(text="b").grid(column=1)
        c = Button(text="c").grid(column=1)
        d = Button(text="d").grid(column=1)
        e = Button(text="e").grid(column=1)
        f = Button(text="f").grid(column=1)
        g = Button(text="g").grid(column=1)
    elif CheckVar1.get() == 1:
        A = Button(text="A").grid(column=1)

CheckVar1.trace("w",trace_method)

window.mainloop()