【发布时间】:2026-02-12 04:25:01
【问题描述】:
我在尝试将变量传递给“simpledialog”框时遇到了一些我一直在编写的代码的问题。但是,当我在__init__ 部分中声明变量时,无法从类中的任何其他方法访问该变量。
我创建了一个简化的工作示例,我在其中尝试将字符串传递给 Entry 框,以便在创建“simpledialog”时,Entry 框已填充。然后可以更改该值并将新值打印到控制台。
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 类的 __init__ 方法中插入 print(number) 行,则该数字将打印到控制台。此外,如果我在 body() 方法中初始化 self.number 变量(例如,self.number = "example"),代码将按预期工作。
我确定我在这里遗漏了一些愚蠢的东西,但如果您能就可能发生的事情提供任何建议,我们将不胜感激。
【问题讨论】:
标签: python variables python-3.x simpledialog