我正在Tkinter制作一个GUI程序并遇到问题。我想要做的是绘制2个复选框和一个按钮。根据用户输入应该进行下一步骤。我的代码的一部分如下所示: -
CheckVar1 = IntVar()
CheckVar2 = IntVar()
self.C1 = Checkbutton(root, text = "C Classifier", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5,width = 20).grid(row=4)
self.C2 = Checkbutton(root, text = "GClassifier", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20).grid(row=5)
self.proceed1 = Button(root,text = "\n Proceed",command = self.proceed(CheckVar1.get(),CheckVar2.get())).grid(row=6)
# where proceed prints the combined values of 2 checkboxes
我得到的错误是典型的,即所选复选框的默认值被打印出来,然后没有进一步的输入。我得到的错误是NullType对象不可调用。
我在网上搜索,我认为答案与lambda事件或咖喱有关。
请帮助..
答案 0 :(得分:1)
您正在将self.proceed(CheckVar1.get(),CheckVar2.get())
的值传递给Button
构造函数,但您可能想要将command
设置为 function 将调用self.proceed(CheckVar1.get(),CheckVar2.get())
并在每次按下按钮时返回一个新的,可能不同的值。您可以使用lambda修复它,或者通过在短回调函数中包装调用。例如,将最后一行替换为:
def callback():
return self.proceed(CheckVar1.get(), CheckVar2.get())
self.proceed1 = Button(root, text="\n Proceed", command=callback).grid(row=6)
这是非常典型的Tkinter。请记住:当您在Tkinter中看到名为command
的变量时,它正在寻找函数,而不是值。
编辑:要清楚:你得到'NullType对象不可调用',因为你已经将command
设置为等于对self.proceed
的单个调用的返回值(这是NullType对象) )。 self.proceed
是一个函数,但它的返回值不是。您需要的是将command
设置为调用self.proceed
的函数。
答案 1 :(得分:0)
就像Peter Milley所说,command
选项需要对函数的引用(即:给它一个函数 name (即:没有括号)。不要试图“内联” “某些东西,创造一个特殊的功能。你的代码将更容易理解和维护。