首页 > 解决方案 > 如何在 tkinter 中启用和禁用按钮?

问题描述

我试图看到,当用户向输入字段添加内容时,我的按钮被启用,然后当用户删除该条目时,我的按钮被禁用

标签: python-3.xtkinter

解决方案


禁用按钮的一种方法是使用以下代码:

button = tkinter.Button(root, text='enable/disable'))
def switchButtonState():
    if (button['state'] == tk.NORMAL):
        button['state'] = tk.DISABLED
    else:
        button['state'] = tk.NORMAL

要从文本小部件中获取输入意味着您必须运行以下代码:

root.after(1000, check_text_box) # I am pretty sure the 1000 is number of milliseconds

after 函数的作用是每 1000 毫秒调用一次 check_text_box 函数

这是使其工作的完整代码:


def check_to_disable_enable():
    text = text_widget_name.get(1.0, tkinter.END)
    if text == '': # If the textbox is empty
        button['state'] = tk.DISABLED # Disables button
    else: # If the textbox is not empty
        button['state'] = tk.NORMAL # Enables button
# Call this function when the frame comes up
root.after(100, check_to_disable_enable)

我意识到这可能有点令人困惑,如果是,请不要问问题。如果这回答了您的问题,请将其标记为已回答。


推荐阅读