我可以从小部件中获取()Widget的IntVariable值吗?

时间:2018-01-08 22:58:44

标签: python python-2.7 tkinter

我试图使用.get()获取Tkinter.Checkbutton变量的值,但是我收到错误。

import Tkinter as tk
class myApp(tk.Tk):
    def __init__(self, parent):
        tk.Tk.__init__(self, parent)
        self.parent = parent
        self.grid()
        self.var = tk.IntVar()
        self.cb = tk.Checkbutton(self.parent, variable=self.var)
        self.cb.bind('<Button-1>', self.useValue)
        print self.var.get() # works
        print self.cb.get() # does not work
        print self.cb.cget('variable') # prints something like PYNUMVAR1 
        print self.cb.cget('variable').get() # error I mention below
        print self.cb.var.get() # error
        print self.cb.val.get() # error

    def useValue(self, event):
        print event.widget.cget('variable').get()) # why not?

if __name__ == '__main__':
    runit = myApp(None)
    runit.mainloop()

我尝试了很多我在stackoverflow和其他教程网站上看到的所有内容的组合。我得到的错误是

AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'get'

IntVar不是&#39; _tkinter.Tcl_Obj&#39;宾语?该对象没有get属性。当我尝试像self这样

在self.var上引发属性错误时
print self.var.crumpet()

控制台让我知道它也是那种类型的对象。 (它确实在我的第一个实验中执行了此操作,但我无法在上面的示例代码中在IntVar实例上重新创建此错误消息,所以我认为这可能是错误的)

我知道我可以在self.var上使用get(),但是如果我通过event参数将小部件传递给回调函数,我希望能够获得它的值。 / p>

如何在不对变量做任何事情的情况下获取Checkbutton的值?我应该避免为它分配变量吗?

3 个答案:

答案 0 :(得分:3)

  

print event.widget.cget(&#39; variable&#39;)。get())#why not?

这只是tkinter的限制。从概念上讲,应该工作,你可以在tcl / tk中做同等的工作,但它不会在tkinter中工作。

换句话说,它是一个错误,无论是在tkinter的设计还是它的实现中,我都不确定是哪个。

  

如何在不对变量做任何事情的情况下获取Checkbutton的值?我应该避免为它分配变量吗?

一个简单但有效的解决方案是附加对小部件的引用:

class myApp(tk.Tk):
    def __init__(...):
        ...
        self.cb.var = self.var
        ...
    def useValue(self, event):
        print event.widget.var.get()

另一个解决方案是记录不足的getvar方法,该方法将tcl变量名称作为参数并返回该值。

例如:

def useValue(self, event):
    widget = event.widget
    varname = str(widget.cget("variable"))
    print widget.getvar(varname)

注意:绑定到<Button-1>表示在设置或取消设置检查按钮之前,将导致回调。它将始终显示以前的值。绑定到<ButtonRelease-1>,或者对变量进行跟踪。后者是首选,因为如果用户通过键盘更改了检查按钮,<ButtonRelease-1>上的绑定将不会触发。

答案 1 :(得分:0)

CheckButton中显示self.var的状态,CheckButton对象没有任何get属性。

        print self.var.get() # Value of CheckButton state
        print self.cb.get() # Checkbutton doesn't have any attribute .get()
        print self.cb.cget('variable') # prints name value stored in tkinter
        print self.cb.cget('variable').get() # self.cb.cget('variable') doesn't have .get attribute
        print self.cb.var.get() # self.cb (checkButton) doesn't have any var attribute
        print self.cb.val.get() # self.cb.val was not declared before

答案 2 :(得分:0)

首先,要意识到Checkbutton没有value选项。它有onvalueoffvalue选项,您也可以设置。下面的代码设置了onvalue的{​​{1}},然后在标签上显示其Checkbuttononvalue

offvalue