使用.get()从另一个类中提取Tkinter变量

2024-10-05 14:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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


Tags: 函数用户importselfappinputapplicationinit
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:31

my_entry不是Application类的属性,所以不能做Application.my_entry,因为它是Application类实例的属性,所以可以做Application().my_entry。您可能可以将Applicationmy_entry的实例添加到__init__PullVariable方法中。我用前者

# ...
class PullVariable:
    def __init__(self, app): # add app here
        self.pulled_entry = app.my_entry.get() # use app here
        print(self.pulled_entry)
# and then
root=Tk()
ui = Application(root)
ui.hello_world()
ui.entry()

pv = PullVariable(ui) # supply PullVariable with instance of Application

相关问题 更多 >