Python/Tkinter:使用按钮更新类变量
这可能是一个愚蠢的问题,但我在这里找不到答案,所以就这样 我正在设置一个Tkinter界面,我只是其中的一个按钮。单击此按钮时,应将变量Python/Tkinter:使用按钮更新类变量,python,user-interface,tkinter,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 =
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")
输出如下所示(重复单击按钮的次数):
为什么它不更新变量?甚至显示“go已更新”
”?
谢谢 您错误地传递了
命令
参数,只需执行以下操作:
self.butGo = Button(top, command=self.goTime)
要引用实例方法/属性,必须执行self.method\u name
(self
只是一种约定)
如果需要传递参数,可以使用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)
您错误地传递了
命令
参数,只需执行以下操作:
self.butGo = Button(top, command=self.goTime)
要引用实例方法/属性,必须执行self.method\u name
(self
只是一种约定)
如果需要传递参数,可以使用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)
最初定义go时,将其定义为self.go最初定义go时,将其定义为self.go