【发布时间】:2021-07-25 17:01:42
【问题描述】:
我刚开始学习 tkinter,遇到了一个问题。我有两个 tkinter 课程。我在一个 tkinter 类的输入字段中输入一个值,并尝试在另一个类的标签中显示它。我已经尝试了很多方法,但无法做到这一点。请如果有人可以帮助我这样做。这是我的代码。
import tkinter
from tkinter import Tk, Toplevel
from tkinter import *
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):
self.root.destroy()
main_window = Tk()
app = second(main_window)
main_window.mainloop()
def return_id(self):
return self.mystring.get()
class second:
def __init__(self, root):
self.root = root
self.root.title('Second window')
self.root.geometry('1350x700+0+0')
id = first.return_id
get_id = Label(self.root, text=id, font=("Times New Roman", 14), bg='white',
fg='black')
get_id.place(x=200, y=350)
if __name__ == '__main__':
main()
我这样做的方式并没有显示实际价值。相反,它给出了
2064283946496return_id
任何帮助将不胜感激。
【问题讨论】:
-
id = first.return_id会将first.return_id的函数引用分配给id。这就是你得到结果的原因。为了获取输入的值,最好在创建时直接将值传递给second类。 -
尝试在
self.root.destroy()之前添加user_input = self.txt_id.get(),然后将该输入作为参数传递给第二个类。现在,您正在尝试在销毁其主服务器后访问self.mystring。self.root.destroy()破坏self.mystring和self.txt_id -
通常我们实例化类然后使用它的方法。在这里,我认为您可以使用
second的def __init__(self, root, id)创建一个参数,然后在self.root.destroy()之前使用id = self.txt_id.get(),然后再使用app = second(main_window,id)
标签: python class user-interface tkinter python-class