正如标题所暗示的那样,是否有一种方法可以在选中复选框时更改复选框上文本的颜色,然后在取消选中该复选框时返回默认颜色?
答案 0 :(得分:1)
是,您可以在Checkbutton
启用时更改文本的颜色。要更改文本的颜色,请使用选项fg
。我做了两个变量off_color
和on_color
。当Checkbutton
关闭时,文本的颜色为red
按钮,当它打开时,颜色为green
。
这是代码:
from tkinter import *
import tkinter
root = Tk()
off_color = "red"
on_color = "green"
def on_check(): #this function will run on click on checkbutton
if cbVar.get() == "1":chbox["fg"] = on_color # if (get current checkbutton state) is "1" then....
else:chbox["fg"] = off_color
cbVar = StringVar(root) #making variable for checkbutton
cbVar.set(0) #turning off the checkbutton (initialy)
chbox = Checkbutton(root,variable = cbVar,text="Check me",command=on_check,fg=off_color) #making the checkbutton
chbox.place(x=0,y=0) #placing the checkbutton
mainloop()