ferryard
ferryard

Reputation: 135

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

Upvotes: 1

Views: 6747

Answers (3)

Vincent Carbonara
Vincent Carbonara

Reputation: 9

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()

Upvotes: 0

user4171906
user4171906

Reputation:

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()

Upvotes: 1

User
User

Reputation: 14863

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.

Upvotes: -2

Related Questions