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

能否在CustomTkinter中设置activeforeground/activebackground?

CustomTkinter中实现按钮点击时的背景/文本颜色更改

CustomTkinter支持实现按钮交互状态(悬停、按下)下的背景和文本颜色更改,但并不使用Tkinter里的activeforeground和activebackground属性,而是通过专门的状态属性来配置:

  • 悬停状态(鼠标停留在按钮上):
    • 用hover_color设置背景色
    • 用text_color_hover设置文本颜色
  • 按下状态(点击按钮时):
    • 用pressed_color设置背景色
    • 用text_color_pressed设置文本颜色

示例代码

import customtkinter as ctk

# 初始化基础设置
ctk.set_appearance_mode("light")
ctk.set_default_color_theme("blue")

app = ctk.CTk()
app.geometry("300x200")

# 创建带状态颜色配置的按钮
test_button = ctk.CTkButton(
    app,
    text="点击测试",
    fg_color="#2d2d2d",       # 默认背景色
    text_color="white",       # 默认文本色
    hover_color="#4a4a4a",    # 悬停时背景色
    text_color_hover="white", # 悬停时文本色
    pressed_color="#1a1a1a",  # 按下时背景色
    text_color_pressed="#f5f5f5" # 按下时文本色
)
test_button.pack(pady=50)

app.mainloop()

如果需要修改已创建按钮的状态颜色,可使用configure方法动态调整:

test_button.configure(
    hover_color="#555555",
    pressed_color="#000000",
    text_color_pressed="#ffffff"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:55:16