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

将Tk脚本转为CTk后按钮state状态判断失效问题求助

修复后的CustomTkinter脚本

问题出在两个核心点:

  1. 变量名Button和CustomTkinter的按钮类CTkButton重名,导致代码逻辑混淆
  2. CustomTkinter中按钮的state属性取值为字符串类型("disabled"/"normal"),而非原生tkinter里的DISABLED常量,直接用DISABLED做比较会触发错误

修复后的代码:

from customtkinter import *

def ChangeState():
    my_button.configure(state="disabled")
    # 使用字符串"disabled"进行状态判断
    if my_button['state'] == "disabled":
        my_button.configure(fg_color="Green")

window = CTk()

# 变量名改为my_button,避免与类名冲突
my_button = CTkButton(window, text="Button", hover=False, command=ChangeState)
my_button.pack()

window.mainloop()

额外提示:在大型脚本中,务必避免使用和内置类/函数重名的变量名;同时CustomTkinter组件的属性规则和原生tkinter存在差异,编写逻辑时需注意对应属性的取值类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 00:03:10