Reputation: 1326
This is probably a silly question, but I couldn't find an answer to it on here, so here goes.
I'm setting up a Tkinter interface, and I'm only one button in. This button, when clicked should change the variable go
to 1
, I have done this by requiring it to call the function getGo(self)
which is in the same class as the init
function where the button was set up.
My problem is that it doesn't run the whole goTime()
function: ie, it doesn't update my variable go
.
init
function:
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")
The output looks like this (repeated the number of times I clicked the button):
It's go time!
It's go time!
It's go time!
It's go time!
Why won't it update the variable? Or even show "go has been updated
"?
Thanks!
Upvotes: 0
Views: 460
Reputation: 4543
You are passing the command
argument incorrectly, just do:
self.butGo = Button(top, command=self.goTime)
To reference an instance method / attribute you must do self.method_name
(self
is just a convention)
If you need to pass arguments, you can use lambda:
command=lambda: self.go_time(5)
command=lambda n: self.go_time(n)
...
although I prefer 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)
Upvotes: 2