Python / Tkinter:使用按钮更新类变量

时间:2018-02-28 18:12:28

标签: python user-interface tkinter

这可能是一个愚蠢的问题,但我在这里找不到答案,所以这里就是。

我正在设置一个Tkinter界面,而我只有一个按钮。点击此按钮时,应将变量go更改为1,我已完成此操作要求它调用函数getGo(self),该函数与设置按钮的init函数位于同一类中。

我的问题是它没有运行整个goTime()函数:即它没有更新我的变量go

init功能:

class New_Toplevel_1:
    go=0
    def __init__(self, top=None):
        self.butGo = Button(top,command=lambda *args: goTime(self))
        self.butGo.place(relx=0.48, rely=0.84, height=41, width=65)
        self.butGo.configure(activebackground="#7bd93b")
        self.butGo.configure(font=font12)
        self.butGo.configure(text='''Go!''')

    def goTime(self):
        print("It's go time!")
        self.go=1
        print("go has been updated")

输出如下(重复按下按钮的次数):

It's go time!
It's go time!
It's go time!
It's go time!

为什么不会更新变量?甚至可以显示" go has been updated"? 谢谢!

1 个答案:

答案 0 :(得分:2)

您正在错误地传递command参数,只需执行:

self.butGo = Button(top, command=self.goTime)

要引用实例方法/属性,您必须self.method_nameself只是一个约定)

如果需要传递参数,可以使用lambda:

command=lambda: self.go_time(5)
command=lambda n: self.go_time(n)
...

虽然我更喜欢functools.partial

from functools import partial

class NewToplevel1:
    go = 0

    def __init__(self, top=None):
        self.butGo = Button(top, command=partial(self.go_time, 5))
        self.butGo.place(relx=0.48, rely=0.84, height=41, width=65)
        self.butGo.configure(activebackground="#7bd93b")

        self.butGo.configure(text='''Go!''')

    def go_time(self, n):
        print("It's go time!")
        self.go = n
        print("go has been updated")
        print(self.go)