猿问

在函数中无法禁用 tkiner 按钮

基本上,我目前正在编写一个 python 程序(技术上它是一个游戏),其中某个(TKinter Widget)按钮只能每 1 秒单击一次。这是我的意思的一个例子:


import time

from tkinter import *

def button_click():

    button["state"] = DISABLED

    print("button clicked! Please wait 1 second...")

    time.sleep(1)

    button["state"] = NORMAL


root = Tk()


button = Button(root, text="Click Me!", command=button_click)


button.pack() #Please Dont Tell Me Not To Use Pack() ; I Use Place()

所以无论如何,例如,当运行这个程序时,如果我一直点击按钮,它会每秒增加 1 个计数。相反,我希望它不计算第一次点击和之后 1 秒之间发生的所有点击。


慕桂英546537
浏览 150回答 2
2回答

ibeautiful

这是因为当按钮被禁用时 tkinter 没有控制,所以它没有更新。例如,您需要button.update()在禁用后调用以强制更新:def button_click():    button["state"] = DISABLED    button.update() # force the update    print("button clicked! Please wait 1 second...")    time.sleep(1)    button["state"] = NORMAL但是,最好使用after()而不是time.sleep():def button_click():    button["state"] = DISABLED    print("button clicked! Please wait 1 second...")    # enable the button after one second    button.after(1000, lambda: button.config(state='normal'))

GCT1015

也许您忘记了代码末尾的“root.mainloop”。import timefrom tkinter import *def button_click():    button["state"] = DISABLED    print("button clicked! Please wait 1 second...")    time.sleep(1)    button["state"] = NORMALroot = Tk()button = Button(root, text="Click Me!", command=button_click)button.pack()root.mainloop()这对我有用。您只能每 1 秒按下一次按钮。
随时随地看视频慕课网APP

相关分类

Python
我要回答