Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Cannot pass arguments from the tkinter widget.after function

Part of the GUI I'm building using tkinter has a pop-up window that says "Please wait while the program is running." then after it finishes the window goes away. I'm using the widget.after command to open the window and run the command. However if I pass the function I call arguments then the pop up window never occurs. Here's an example:

def backupWindow
    self.restoreCB = Toplevel()

    message = "Please wait while backup runs"
    Label(self.restoreCB, text=message, padx=100, pady=20).pack()

    widget.after(10, self.runBackup)

def runBackup(self):
    <backup code>
    self.backupCB.destroy()

This runs fine and does what I want it to do, the window pops up while the backup runs, then the window closes after the backup. However, If I pass the and argument from the widget.after like the code below, the "please wait" message never shows up.

def backupWindow
    self.restoreCB = Toplevel()

    message = "Please wait while backup runs"
    Label(self.restoreCB, text=message, padx=100, pady=20).pack()

    widget.after(10, self.runBackup(mybackup))

def runBackup(self,mybackup):
    <backup code using mybackup>
    self.backupCB.destroy()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do this:

widget.after(10, self.runBackup(mybackup))

... You are telling Tkinter "run the command runBackup, and when it returns, use the result as an argument to after". Because runBackup returns None, the above is equivalent to:

self.runBackup(mybackup)
widget.after(10, None)

Instead, you want to give after a reference to the function, rather than calling the function. If the command needs arguments, those can be given to after as additional arguments.

For example:

widget.after(10, self.runBackup, mybackup)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...