【问题标题】:Tkinter - StringVar() trace not executing commandTkinter - StringVar() 跟踪未执行命令
【发布时间】:2017-05-13 20:29:06
【问题描述】:

我编写此代码是为了作为版本管理器,但它不执行命令changeDir()。为什么?

https://pastebin.com/VSnhzRzF

【问题讨论】:

标签: python tkinter


【解决方案1】:

您忘记将“名称”参数传递给changeDir 函数。而且也不例外,因为你的说法没有效果!

代表问题的片段:

import sys


def exec_smth():
    # execution without effect
    exec('write_smth')

    try:
        # execution with exception because of missing argument
        exec('write_smth()')
    except TypeError as error:
        # now we pass an argument
        exec('write_smth("I failed because of %s" % error )')


def write_smth(smth):
    sys.stdout.write(smth)

exec_smth()

无论如何,由于垃圾收集器,在您的 __init__ 函数之外根本没有 StringVars,因此您的代码无论如何都会失败!

还有更多问题,因为您永远不会将任何sv{} 绑定到小部件并期望得到回报!不过好吧,让我们试着用exec做事:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entries = []

        for _ in range(5):
            exec('self.sv{} = tk.StringVar()'.format(_))
            exec('self.sv{}.trace("w", self.change_sv)'.format(_))
            exec('self.entries.append(tk.Entry(self, text="", textvariable=self.sv{}))'.format(_))

        for entry in self.entries:
            entry.pack()

    def change_sv(*args):
        # get id of a variable (you can't rely on that (0-9)!)
        idx = args[1][-1:]
        # get new value
        value = getattr(args[0], 'sv{}'.format(idx)).get()
        # result
        print('Value changed in self.sv%s to %s!' % (idx, value))

app = App()
app.mainloop()

输出:

如您所见 - 我们总是需要对 StringVars 的引用,我认为带有它们列表的选项要好得多!

注意:如果你需要传递一些东西给回调函数——使用lambda 函数!所有代码均使用 Python 3 测试。

链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-18
    • 2017-01-08
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2020-05-17
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多