在tkinter中的窗口类之间传递信息可以通过以下几种方式实现:
import tkinter as tk
class Window1(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Window 1")
self.button = tk.Button(self, text="Open Window 2", command=self.open_window2)
self.button.pack()
def open_window2(self):
global shared_data
shared_data = "Hello from Window 1"
self.destroy()
window2 = Window2()
window2.mainloop()
class Window2(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Window 2")
label = tk.Label(self, text=shared_data)
label.pack()
shared_data = ""
window1 = Window1()
window1.mainloop()
import tkinter as tk
class Window1(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Window 1")
self.button = tk.Button(self, text="Open Window 2", command=self.open_window2)
self.button.pack()
def open_window2(self):
self.destroy()
window2 = Window2(self.update_label)
window2.mainloop()
def update_label(self, data):
self.label.config(text=data)
class Window2(tk.Tk):
def __init__(self, callback):
tk.Tk.__init__(self)
self.title("Window 2")
self.callback = callback
self.entry = tk.Entry(self)
self.entry.pack()
self.button = tk.Button(self, text="Send Data", command=self.send_data)
self.button.pack()
def send_data(self):
data = self.entry.get()
self.callback(data)
self.destroy()
window1 = Window1()
window1.mainloop()
import tkinter as tk
class SharedData:
def __init__(self):
self.data = ""
class Window1(tk.Tk):
def __init__(self, shared_data):
tk.Tk.__init__(self)
self.title("Window 1")
self.shared_data = shared_data
self.button = tk.Button(self, text="Open Window 2", command=self.open_window2)
self.button.pack()
def open_window2(self):
self.destroy()
window2 = Window2(self.shared_data)
window2.mainloop()
class Window2(tk.Tk):
def __init__(self, shared_data):
tk.Tk.__init__(self)
self.title("Window 2")
self.shared_data = shared_data
self.entry = tk.Entry(self)
self.entry.pack()
self.button = tk.Button(self, text="Send Data", command=self.send_data)
self.button.pack()
def send_data(self):
data = self.entry.get()
self.shared_data.data = data
self.destroy()
shared_data = SharedData()
window1 = Window1(shared_data)
window1.mainloop()
这些方法可以根据具体的需求选择使用,通过全局变量、回调函数或共享对象,在tkinter中的窗口类之间可以方便地传递信息。
领取专属 10元无门槛券
手把手带您无忧上云