使用 'simpledialog' 时声明的变量未初始化

Declared variables not initialised when using 'simpledialog'

我在尝试将变量传递给 'simpledialog' 框的部分代码中遇到问题。但是,当我在 __init__ 部分中声明变量时,无法从 class.

中的任何其他方法访问该变量

我创建了一个简化的工作示例,其中我试图将字符串传递给 Entry 框,以便在创建 'simpledialog' 时,条目 框已填充。然后可以更改该值并将新值打印到控制台。

from tkinter import *
from tkinter.simpledialog import Dialog


class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        Button(parent, text="Press Me", command=self.run).grid()

    def run(self):
        number = "one"
        box = PopUpDialog(self, title="Example", number=number)
        print(box.values)

class PopUpDialog(Dialog):
    def __init__(self, parent, title, number, *args, **kwargs):
        Dialog.__init__(self, parent, title)
        self.number = number

    def body(self, master):
        Label(master, text="My Label: ").grid(row=0)
        self.e1 = Entry(master)
        self.e1.insert(0, self.number)  # <- This is the problem line
        self.e1.grid(row=0, column=1)

    def apply(self):
        self.values = (self.e1.get())
        return self.values

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

当代码为 运行 并且按下 'Press Me' 按钮时,我收到以下错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:/Python/scratch.py", line 14, in run
    box = PopUpDialog(self, title="Example", number=number)
  File "C:/Python/scratch.py", line 20, in __init__
    Dialog.__init__(self, parent, title)
  File "C:\Python34\lib\tkinter\simpledialog.py", line 148, in __init__
    self.initial_focus = self.body(body)
  File "C:/Python/scratch.py", line 26, in body
    self.e1.insert(0, self.number)
AttributeError: 'PopUpDialog' object has no attribute 'number'

如果我注释掉 self.e1.insert(0, self.number),代码将以其他方式运行。

关于 'simpledialog' 的文档似乎很少,我一直在使用 effbot.org 上的示例来尝试了解有关对话框的更多信息。

附带说明一下,如果我在 PopUpDialog class 的 __init__ 方法中插入 print(number) 行,该数字将打印到控制台。此外,如果我在 body() 方法中初始化 self.number 变量(例如,self.number = "example"),代码将按预期工作。

我确定我在这里遗漏了一些愚蠢的东西,但如果您能就可能发生的事情提供任何建议,我们将不胜感激。

问题出在您的 PopUpDialog class,在函数 __init__ 中,您调用了调用主体方法的行 Dialog.__init__(self, parent, title)。问题是您在下一行初始化了 self.number,这就是为什么 self.number 还没有在 body 方法中初始化的原因。

如果你换行它会为你工作,就像这样:

class PopUpDialog(Dialog):
    def __init__(self, parent, title, number, *args, **kwargs):
        self.number = number
        Dialog.__init__(self, parent, title)

编辑:

正如您在对话框的 __init__ 方法中看到的那样,上面一行:

self.initial_focus = self.body(body) 调用你的 body 方法。