我尝试使用上面的 Rushy Panchal 示例使用两个以上的窗口。目的是改变调用更多带有不同小部件的窗口。butnew 函数创建不同的按钮来打开不同的窗口。您将包含窗口的类的名称作为参数传递(第二个参数不是必需的,我把它放在那里只是为了测试可能的用途。从另一个窗口继承共同的小部件可能会很有趣。
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.frame = tk.Frame(self.master)
self.butnew("Window 1", "ONE", Demo2)
self.butnew("Window 2", "TWO", Demo3)
self.frame.pack()
def butnew(self, text, number, _class):
tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()
def new_window(self, number, _class):
self.newWindow = tk.Toplevel(self.master)
_class(self.newWindow, number)
class Demo2:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
class Demo3:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
self.label2.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
新窗口只打开一次
为了避免有机会多次按下具有多个窗口的按钮......这是同一个窗口,我制作了这个脚本(也看看这个页面)
import tkinter as tk
def new_window1():
global win1
try:
if win1.state() == "normal": win1.focus()
except:
win1 = tk.Toplevel()
win1.geometry("300x300+500+200")
win1["bg"] = "navy"
lb = tk.Label(win1, text="Hello")
lb.pack()
win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()