【问题标题】:Checkbutton in tkinter is not storing values into variablestkinter 中的 Checkbutton 没有将值存储到变量中
【发布时间】:2018-02-10 01:31:31
【问题描述】:

我刚刚在 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()

变量spam 为空,无论我的checkbutton 是选中还是未选中。查看示例和文档也是一个死胡同。为什么我的变量还是空的?

【问题讨论】:

  • 您在创建小部件后大约一毫秒打印该值。用户甚至还没有看到 UI,更不用说与之交互了。

标签: python python-3.x tkinter ttk


【解决方案1】:

替换:

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'])

【讨论】:

  • 感谢您的热心帮助!这正是问题所在。
猜你喜欢
  • 2018-10-26
  • 2015-07-12
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 2020-11-30
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多