python - tkinter 中的检查按钮未将值存储到变量中

标签 python python-3.x tkinter ttk

我只是在 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 既不是关闭值也不是打开值),但很难注意到对于 版本(如果有),替换:

checkbutton = ttk.Checkbutton(...

与:

checkbutton = Checkbutton(...

使用 中的默认复选按钮,显示得更加明显。

另请注意,需要使用 Checkbutton 才能调用 spam.set(checkbutton['onvalue'])spam.set(checkbutton ['offvalue']).

关于python - tkinter 中的检查按钮未将值存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716360/

相关文章:

python - 如何在 tkinter Canvas 中嵌入 matplotlib 图形时获得 (3d) 交互性

python - 如何在 Python 3.4.3 的 tkinter 中关闭窗口?

python - 如何在 Python 中获取绝对文件路径

python - Django 模板将 HTML 参数渲染为文本

Python 绘图线链接值似乎从最后一个点绕回到第一个点

python-3.x - 无法在 python 中迭代 Azure ADGroupPaged 对象

python - 如何在屏幕上显示和更新分数?

python - 这是什么错误? linux 下的 python 脚本

python - 你将如何在 python 中打印数字 1、2、3、4、5、6、7、8、18、19、20、21、22、23、24?

python - 在 Python 3 中获取第一项 `OrderedDict` 的最短方法