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
相关产品推荐
相关产品推荐

