Python / Tkinter-选中复选框时,更改复选框文本的颜色吗?

时间:2018-08-14 06:50:23

标签: python checkbox text tkinter colors

正如标题所暗示的那样,是否有一种方法可以在选中复选框时更改复选框上文本的颜色,然后在取消选中该复选框时返回默认颜色?

1 个答案:

答案 0 :(得分:1)

是,您可以在Checkbutton启用时更改文本的颜色。要更改文本的颜色,请使用选项fg。我做了两个变量off_coloron_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()

关闭checkbutton时:
Off

打开checkbutton时:
On