为了账号安全,请及时绑定邮箱和手机立即绑定

在函数中无法禁用 tkiner 按钮

在函数中无法禁用 tkiner 按钮

慕桂英546537 2023-06-13 10:39:45
基本上,我目前正在编写一个 python 程序(技术上它是一个游戏),其中某个(TKinter Widget)按钮只能每 1 秒单击一次。这是我的意思的一个例子: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() #Please Dont Tell Me Not To Use Pack() ; I Use Place()所以无论如何,例如,当运行这个程序时,如果我一直点击按钮,它会每秒增加 1 个计数。相反,我希望它不计算第一次点击和之后 1 秒之间发生的所有点击。
查看完整描述

2 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

这是因为当按钮被禁用时 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'))


查看完整回答
反对 回复 2023-06-13
?
GCT1015

TA贡献1827条经验 获得超4个赞

也许您忘记了代码末尾的“root.mainloop”。


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


root.mainloop()

这对我有用。您只能每 1 秒按下一次按钮。


查看完整回答
反对 回复 2023-06-13
  • 2 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信