【问题标题】:Can't get tkinter's StringVar's trace method to work无法让 tkinter 的 StringVar 的跟踪方法工作
【发布时间】:2016-12-18 21:18:57
【问题描述】:

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

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":

即使经过很多“堆栈溢出”,我仍然无法让它工作。如何避免/修复此错误?

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多