简体   繁体   中英

How to set on/off value with checkbutton in Tk/Tcl

I am currently learning about the usage of widgets in the tkinter package. And uncertain as to how the on/off value works in the checkbutton widget.

My written code is as follows:

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Checkbutton")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

measureSystem = StringVar()
cmd1 = lambda *args: print(str(measureSystem) + ' selected')
check = ttk.Checkbutton(mainframe, text='Use Metric',
                        command=cmd1, variable=measureSystem,
                        onvalue='metric', offvalue='imperial')

However when I do check and uncheck the checkbutton, what is returned is the following, regardless of the state the checkbutton is in:

PY_VAR1 selected

I understand that the onvalue and offvalue is supposed to be stored in the measureSystem variable depending on the state of the checkbutton.

Why is this not the case here?

Try changing:

str(measureSystem)

to:

str(measureSystem.get())

as StringVar uses .set() and .get() to access the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM