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

Tkinter Checkbutton切换状态时背景色异常问题求助

解决Tkinter Checkbutton切换状态时背景色变化问题

当使用自定义图片替换Checkbutton勾选框时,要保持on/off状态下背景色一致,只需在创建Checkbutton时补充几个关键参数:

  • 添加selectcolor=lightpurple:强制选中状态的背景色与默认背景一致
  • 添加activebackground=lightpurple:确保鼠标交互时背景色不变
  • 添加highlightthickness=0:移除控件的高亮边框,避免背景色异常

修改后的完整代码:

from tkinter import *
import tkinter.font as font      # 用于设置不同字体

def showCheckbuttons():
    order_label = Label(lights_frame, text="Select Light(s)",
                        font=font_large, bd=10, padx=80, bg=lightpurple)
    order_label.grid(row=1, column=0, columnspan=2)

    light_list = ["Front  ", "Drive  ", "Back   ", "Side   "]
    light_dict = {}
    
    r=2 # 起始行
    c=0 # 起始列
    # 批量创建Checkbutton并存入字典
    for  i, light_item in  enumerate(light_list):

        # 创建Checkbutton,补充背景色相关参数
        light_dict[light_item] = Checkbutton(lights_frame, text=light_item, image=ON_img,
                                            selectimage=OFF_img, compound='right',borderwidth=0,
                                            font=font_large, bg=lightpurple, indicatoron=False,
                                            selectcolor=lightpurple, activebackground=lightpurple,
                                            highlightthickness=0)

        # 为每个Checkbutton绑定独立的IntVar
        light_dict[light_item].var = IntVar()

        # 设置Checkbutton的关联变量
        light_dict[light_item]['variable'] = light_dict[light_item].var

        # 布局Checkbutton
        light_dict[light_item].grid(row=r, column=c)
        r=r+1


root=Tk()
lightpurple= '#d0bafe' 
root.configure(bg=lightpurple)
width, height = 500, 420

# 创建容器Frame
lights_frame = Frame(root, bg=lightpurple, width=500, height=420)

# 加载Checkbutton的状态图片
ON_img = PhotoImage(file='ON_small2.png')
OFF_img = PhotoImage(file='OFF_small2.png')

# 创建字体样式
font_large = font.Font(family='Courier', size=24, weight='bold')

showCheckbuttons()
lights_frame.grid()

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:37:10