简体   繁体   English

执行命令时禁用Tkinter按钮

[英]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. 我想在执行命令时禁用tk inter按钮,并在命令执行完成后将其启用。 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. 我更喜欢使用Tkinter的“之后”方法,因此可以在5秒倒计时的同时完成其他操作。 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. 使用pack_forget()禁用,然后使用pack()重新启用。 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. 更新按钮并将执行传递回Tkinter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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