我一直在努力将一个变量传递给'simpledialog'框的一些代码存在问题。但是,当我在__init__
部分声明变量时,该变量不能从该类中的任何其他方法访问。使用'simpledialog'时声明的变量未初始化
我已经创造了一种我试图将字符串传递到项框,以便创建“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()
当代码运行,并且“按我”按钮被按下时,我收到以下错误信息:
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)
行,该编号将打印到控制台。另外,如果我在正文()方法中初始化self.number
变量(例如,self.number = "example"
),则代码将按预期工作。
我敢肯定,我在这里错过了一些愚蠢的东西,但如果你能提供任何关于可能发生什么的建议,那将是非常感谢。
非常好!很简单!非常感谢您的帮助! – skyhammer
不客气。 –