我只是在 tkinter 中执行我的第一步,但我一直在试图找出为什么这段代码不起作用:
from tkinter import *
from tkinter import ttk
root = Tk()
spam = StringVar()
checkbutton = ttk.Checkbutton(
root, text="SPAM?", variable=spam, onvalue="Yes, SPAM!", offvalue="Boo, SPAM!")
checkbutton.pack()
print(spam.get())
root.mainloop()
无论我的checkbutton
是否选中,变量spam
都是空的。查看示例和文档也是一个死胡同。为什么我的变量仍然为空?
最佳答案
替换:
print(spam.get())
与:
checkbutton['command'] = lambda arg=spam: print(arg.get())
为了查看变量确实存储了值。
<小时/>问题是当您的 print
被调用时 spam.get()
等于 ""
时:
spam = StringVar()
等同于:
spam = StringVar(value="")
<小时/>
checkbutton
最初处于默认的既不打开也不关闭状态(因为 spam
既不是关闭值也不是打开值),但很难注意到对于 ttk版本(如果有),替换:
checkbutton = ttk.Checkbutton(...
与:
checkbutton = Checkbutton(...
使用 tkinter 中的默认复选按钮,显示得更加明显。
另请注意,需要使用 Checkbutton
才能调用 spam.set(checkbutton['onvalue'])
或 spam.set(checkbutton ['offvalue'])
.
关于python - tkinter 中的检查按钮未将值存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716360/