我正在编写一个Tkinter应用程序,它要求用户显示的部分存在于两个不同的类中,这两个类都是从另一个文件导入的。我需要获取一段用户输入并将其从一个类传递到另一个类。在下面的玩具示例中,用户应该在my_entry_input
中键入一些内容,然后类PullVariable
应该访问这些内容
代码如下。我有一些想法,比如使用globals或者在原始类中创建一个函数来获取变量,然后把它们传回来。在所有情况下,我得到:
AttributeError: type object 'Application' has no attribute 'my_entry'
我能想到的最佳解决方案是创建一个响应绑定的函数,然后从该函数将.get()
传递给另一个类。我的感觉是tkinter不喜欢课间的.get()
感谢社区的帮助
主要
from import_test1 import *
root=Tk()
ui = Application(root)
ui.hello_world()
ui.entry()
pv = PullVariable()
if __name__ == '__main__':
root.mainloop()
导入的代码
from tkinter import *
from tkinter import ttk
class Application(Frame):
def __init__(self, parent, *args, **kwargs):
print('Application init')
Frame.__init__(self, parent, *args, **kwargs)
self.parent=parent
self.parent.grid()
def entry(self):
self.my_entry = StringVar(self.parent)
my_entry_input = Entry(self.parent, textvariable=self.my_entry,
width=16)
my_entry_input.bind('<FocusOut>', self.show_entry)
my_entry_input.grid(column=0, row=1)
self.show_label = Label(self.parent, text = '')
self.show_label.grid(column=0, row=2)
def hello_world(self):
print('hello world')
self.hw = Label(self.parent, text='Hello World!')
self.hw.grid(column=0, row=0)
def show_entry(self, event):
PullVariable(Application).find_entry()
class PullVariable:
def __init__(self, app):
self.app = app
print('Pull initiated')
def find_entry(self, event=None):
self.pulled_entry = self.app.my_entry.get()
self.app.show_label['text'] = self.pulled_entry
my_entry
不是Application
类的属性,所以不能做Application.my_entry
,因为它是Application
类实例的属性,所以可以做Application().my_entry
。您可能可以将Application
或my_entry
的实例添加到__init__
的PullVariable
方法中。我用前者相关问题 更多 >
编程相关推荐