简体   繁体   中英

Disable Tkinter button while executing command

I want to disable tk inter button when executing command and enable it back once the command execution finished. I have tried this code, but it seems not working.

from Tkinter import *
import time

top = Tk()
def Run(object):
    object.config(state = 'disabled')
    print 'test'
    time.sleep(5)
    object.config(state = 'normal')

b1 = Button(top, text = 'RUN', command = lambda : Run(b1))
b1.pack()

top.mainloop()

The command execution run well, but every time I click the button when the command is being executed, 'test' appears in the console right after the Run function finished. Which mean the button is not disabled when the Run function is being executed. Any suggestion to fix this problem?

Thanks in advance

I prefer to utilize Tkinter's "after" method, so other things can be done while the 5 seconds are counting down. In this case that is only the exit button.

from Tkinter import *
##import time
from functools import partial

top = Tk()

def Run(object):
    if object["state"] == "active":
        object["state"] = "disabled"
        object.after(5000, partial(Run, object))
    else:
        object["state"] = "active"
    print object["state"]

b1 = Button(top, text = 'RUN')
b1.pack()
## pass b1 to function after it has been created
b1["command"] = partial(Run, b1)
b1["state"]="active"

Button(top, text="Quit", command=top.quit).pack()

top.mainloop()

Use pack_forget() to disable and pack() to re-enable. This causes "pack" window manager to temporarily "forget" it has a button until you call pack again.

from Tkinter import *
import time

top = Tk()
def Run(object):
    object.pack_forget()
    print 'test'
    time.sleep(5)
    object.pack()

b1 = Button(top, text = 'RUN', command = lambda : Run(b1))
b1.pack()

top.mainloop()

You need

object.config(state = 'disabled')
b1.update()
time.sleep(5)
object.config(state = 'normal')
b1.update()

to update the button and pass execution back to Tkinter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM