我刚刚开始学习 tkinter 并遇到了一个问题。我有两个 tkinter 类(class)。我正在一个 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()
我这样做的方式没有显示实际值(value)。相反它给2064283946496return_id
任何帮助将不胜感激。
最佳答案
您可以做的是将第一个类对象作为参数传递给第二个类初始化器,然后在其上调用该方法。这样的事情似乎有效 -:
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, self)
main_window.mainloop()
def return_id(self):
return self.mystring.get()
class second:
def __init__(self, root, first):
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()
关于python - 访问另一个 tkinter 类的输入字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366293/