You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter中实现按钮点击后禁用变灰且显示Booked的方法

Tkinter实现餐桌预订按钮点击后置灰禁用效果

问题背景

开发餐厅管理系统餐桌预订模块时,已完成预订按钮基础布局配置,需要实现点击按钮后按钮变为灰色不可点击状态、按钮文本切换为“Booked”的交互效果,初始代码如下:

window = Tk()
window.title("Restaurant Manager V2")
window.geometry("600x300")
#setup tkinter label
label1 = Label(window, text="Click button to book table")
label1.grid(row=0, column=1, sticky=W)
#setup tkinter button
def button_click():


button1 = Button(window, text="Table 1", width=5, command=button_click)
button1.grid(row=2, column=0, sticky=W)
window.mainloop()

实现步骤

  • 补充缺失的Tkinter模块导入语句,否则代码无法运行
  • 在按钮绑定的button_click()回调函数中,通过按钮组件的config()方法修改属性:
    • 将state参数设为DISABLED,按钮会自动变为灰色禁用状态,不再响应点击
    • 将text参数设为"Booked",替换原有的“Table 1”文本

完整可运行代码

from tkinter import *

window = Tk()
window.title("Restaurant Manager V2")
window.geometry("600x300")
# 配置提示标签
label1 = Label(window, text="Click button to book table")
label1.grid(row=0, column=1, sticky=W)

# 按钮点击回调函数
def button_click():
    button1.config(state=DISABLED, text="Booked")

# 配置预订按钮
button1 = Button(window, text="Table 1", width=5, command=button_click)
button1.grid(row=2, column=0, sticky=W)

window.mainloop()

运行代码后点击“Table 1”按钮,即可看到按钮立即置灰、文本切换为“Booked”的效果。

内容的提问来源于stack exchange,提问作者DenM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 16:06:24