以下是一个示例代码,展示了如何使用Tkinter的Checkbutton保留其值:
import tkinter as tk
def toggle_checkbutton():
if var.get() == 0:
var.set(1)
else:
var.set(0)
def print_value():
print(var.get())
root = tk.Tk()
var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Check Button", variable=var, command=print_value)
checkbutton.pack()
toggle_button = tk.Button(root, text="Toggle", command=toggle_checkbutton)
toggle_button.pack()
root.mainloop()
在这个示例中,我们创建了一个Checkbutton和一个Button。当点击Checkbutton时,它将调用print_value函数来打印当前Checkbutton的值。我们还创建了一个Toggle按钮,用于切换Checkbutton的值。
无论发生什么事件,Checkbutton始终保持其值。当点击Toggle按钮时,它会切换Checkbutton的值,并且在每次点击Checkbutton时,它的值都会被打印出来。
这里使用了一个IntVar变量(var)来保存Checkbutton的值。当点击Checkbutton时,它的值会被更新为0或1,而不管发生什么事件,它的值始终保留。