检查按钮值不变

时间:2016-01-23 16:34:51

标签: python-2.7 tkinter

我试图通过将1或0(作为整数)传递给此函数来为checkbutton设置一个值。但是,检查按钮的状态没有变化。请帮忙。

    def change_On_Off_state(*args):
        CheckVar1 = IntVar()
        CheckVar1.set(*args)
        OnOff = Checkbutton(label2, text = "On", variable = CheckVar1, onvalue = 1, offvalue = 0, height=1, width = 10,anchor = W, bg='Light Blue')
        OnOff.grid(row = 4, column = 2, padx = 10, sticky = W)
        #CheckVar1.trace_variable("w", On_Off_state)

1 个答案:

答案 0 :(得分:0)

可能问题是因为CheckVar1是局部变量,当你离开函数时它不存在。

使用全局变量,它将起作用。

from tkinter import *

# --- functions ---

def change_On_Off_state(*args):
    CheckVar1.set(*args)
    OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0, height=1, width=10, anchor=W, bg='Light Blue')
    OnOff.grid(row=4, column=2, padx=10, sticky=W)
    #CheckVar1.trace_variable("w", On_Off_state)

# --- main ----

root = Tk()

CheckVar1 = IntVar() # global

change_On_Off_state(1)

# "start the engine"
root.mainloop()

我认为你不必创建新的Checkbutton()来改变状态。仅创建CheckbuttonCheckVar一次,并且只使用`CheckVar1.set(...)多次。

from tkinter import *

# --- functions ---

def change_On_Off_state(*args):
    CheckVar1.set(*args)
    #CheckVar1.trace_variable("w", On_Off_state)

def change_on_button_press():
    if CheckVar1.get() == 1:    
        CheckVar1.set(0)
    else:
        CheckVar1.set(1)

# --- main ----

root = Tk()

# create only once
CheckVar1 = IntVar() # global

# create only once
OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0)
OnOff.grid()

# use many times
change_On_Off_state(1)

# use button to on/off checkbutton
btn = Button(root, text="On / Off", command=change_on_button_press)
btn.grid()

# "start the engine"
root.mainloop()