无法使用tkinter的StringVar跟踪方法

时间:2016-08-12 00:39:23

标签: python python-3.x tkinter

每当我尝试运行我的代码时,看起来有点像这样:

from tkinter import OptionMenu, StringVar, Tk

class Foo(OptionMenu):

    def __init__(self, master, options):
        self.bar = StringVar()
        self.bar.set(options[0])
        self.bar.trace("w", lambda: self.mouseCallback("foobar"))
        super().__init__(master, self.bar, *options)

    def mouseCallback(self, baz):
        print(baz)

def mainCycle():
    while True:
        root.update()

if __name__ == "__main__":
    opts = ["A", "LONG", "LIST", "OF", "OPTIONS"]
    root = Tk()
    foobarbaz = Foo(root, opts)
    foobarbaz.pack()
    mainCycle()

我收到以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 3285, in __call__
    self.__var.set(self.__value)
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 260, in set
    return self._tk.globalsetvar(self._name, value)
_tkinter.TclError: can't set "PY_VAR0":

即使在很多" Stack Overflowing"之后,我仍然无法让它发挥作用。如何避免/修复此错误?

1 个答案:

答案 0 :(得分:3)

StringVar.trace()的回调函数的签名应该类似于def callback(*args),因此您在StringVar.trace()中使用的lambda应该更改为:

self.bar.trace("w", lambda *args: self.mouseCallback("foobar"))