Tkinter跨类值传递:如何将Entry输入值跨类传递至Label展示
跨类取值失效的核心原因
- 取值逻辑错误:在
second类中写的id = first.return_id,既没有通过类实例绑定方法、也没有加括号触发方法执行,只是把类里的方法对象本身赋值给了变量,因此这个变量存储的是方法的内存地址,也就是你看到的带一串数字的异常输出。 - 传值链路断裂:第一个窗口点击按钮跳转时,直接销毁原窗口、初始化新窗口,全程没有把
first类中Entry存储的输入值传递给second类的构造方法,第二个类没有可读取的实际值来源。
可直接运行的修正代码
import tkinter from tkinter import Tk, Label, Entry, Button def main(): main_window = Tk() app = first(main_window) main_window.mainloop() class first: def __init__(self, root): self.root = root self.root.title('First window') self.root.geometry('1350x700+0+0') single_id = Label(self.root, text="Enter id", font=("Times New Roman", 14), bg='white', fg='black') single_id.place(x=200, y=200) self.mystring = tkinter.StringVar(self.root) self.txt_id = Entry(self.root, textvariable=self.mystring, font=("Times New Roman", 14), bg='white') self.txt_id.place(x=300, y=200, width=280) btn_search = Button(self.root, command=self.second_window, font=("Times New Roman", 15, 'bold'), text='Get Id') btn_search.place(x=300, y=400, width=220, height=35) def second_window(self): # 调用实例方法获取Entry的实际输入值 input_id = self.return_id() self.root.destroy() main_window = Tk() # 将获取到的输入值作为参数传入第二个类 app = second(main_window, input_id) main_window.mainloop() def return_id(self): return self.mystring.get() class second: # 新增接收传入参数的定义 def __init__(self, root, passed_id): self.root = root self.root.title('Second window') self.root.geometry('1350x700+0+0') # 直接使用传入的实际值作为Label的文本 id_text = passed_id get_id = Label(self.root, text=id_text, font=("Times New Roman", 14), bg='white', fg='black') get_id.place(x=200, y=350) if __name__ == '__main__': main()
关键改动说明
- 跳转窗口时,先在
first类的实例上调用self.return_id()拿到真实输入值,再执行窗口销毁、新窗口初始化操作。 - 调整
second类的初始化方法签名,增加passed_id形参,接收从第一个窗口传递过来的输入值,不再直接访问first类的方法引用。 - 清理冗余的重复导入语句,避免命名冲突。
内容的提问来源于stack exchange,提问作者Anmol
相关产品推荐
相关产品推荐

