python - Buttons activate on creation, then do not work -
i'm neew language, , i'm lost.
from tkinter import * class app: def __init__(self,master): self.var = "" frame = frame(master) frame.pack() self.action = button(frame,text="action",command=self.doaction()) self.action.pack(side=left) def doaction(self): print(self.var) root = tk() app = app(root) root.mainloop()
command=self.doaction()
call doaction
@ time line run (i.e. @ creation). need remove parentheses function isn't called until button calls it:
self.action = button(frame,text="action",command=self.doaction)
to pass argument (which know @ creation time) function, can use lambda (anonymous function):
self.action = button(frame,text="action",command=lambda: self.doaction(x))
this creates new function calls self.doaction(x)
. equivalently, can use named function:
def button_action(): self.doaction(x) self.action = button(frame,text="action",command=button_action)
Comments
Post a Comment