[英]Accessing a variable from a different class - custom dialog
I am trying to create a dialog that will get the a social security number (or simular input) from a pop up dialog, but when I try I get an error saying that the class does not have that attribute. 我正在尝试创建一个对话框,该对话框将从弹出的对话框中获取社会保险号(或模拟输入),但是当我尝试尝试时,出现一个错误,提示该类没有该属性。 Here is the code:
这是代码:
from Tkinter import *
class App:
def __init__(self, master):
b = Button(text="Click for social dialog", command=self.getSocial)
b.grid(row=0, column=0)
def getSocial(self):
d = socialDialog(root)
print d.social
class socialDialog:
def __init__(self, master):
self.top = Toplevel()
Label(self.top, text='Social Security #: ').grid(row=0, column=0)
self.entry = Entry(self.top)
self.entry.grid(row=0, column=1)
self.entry.focus_set()
self.top.bind('<Key>', self.formatData)
self.top.bind('<Return>', self.ok)
def formatData(self, master):
currentData = self.entry.get()
if len(currentData) == 3:
self.entry.insert(3, '-')
elif len(currentData) == 6:
self.entry.insert(6, '-')
elif len(currentData) > 11:
self.entry.delete(-1, END)
def ok(self, master):
self.social = self.entry.get()
self.top.destroy()
root = Tk()
app = App(root)
root.mainloop()
The problem is your socialDialog
class is only assigned a social
attribute after you press Return, which invokes the ok
method. 问题是,仅在您按Return键(调用
ok
方法) 后才为socialDialog
类分配social
属性。 Therefore when you call getSocial
, which instantiates a socialDialog
, and then immediately access the social
attribute, the social
attribute in the socialDialog
instance doesn't exist yet. 因此,当您调用
getSocial
实例化socialDialog
,然后立即访问social
属性时, socialDialog
实例中的social
属性尚不存在。
I'm not sure what your long term goals for this code are, but an immediate fix would be to change the getSocial
function thusly: 我不确定该代码的长期目标是什么,但是一个直接的解决方法是更改
getSocial
函数:
def getSocial(self):
d = socialDialog(root)
# print d.social
then add 然后加
print self.social
to the ok
method. ok
方法。
The problem is that print
is executed immediately after the dialog is shown, because the dialog is not shown modally. 问题是显示对话框后立即执行
print
,因为对话框没有模态显示。
To fix that, try something like this: 要解决此问题,请尝试如下操作:
d = socialDialog(root)
root.wait_window(d.top)
print d.social
But note that the error will still occur if the dialog is closed without entering anything. 但是请注意,如果在不输入任何内容的情况下关闭对话框,仍然会发生错误。 To prevent that, make sure the
social
attribute has a default value: 为避免这种情况,请确保
social
属性具有默认值:
class socialDialog:
social = None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.