gpt4 book ai didi

python - 用于多个窗口的 Tkinter 示例代码,为什么按钮无法正确加载?

转载 作者:IT老高 更新时间:2023-10-28 22:02:51 33 4
gpt4 key购买 nike

我正在编写一个程序,它应该:

  1. 按下按钮打开一个窗口。
  2. 按下另一个按钮关闭新打开的窗口。

我正在使用类,以便以后可以将代码插入到更大的程序中。但是,我的按钮无法正确加载。

import tkinter as tk

class Demo1(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
self.pack()
self.master.title("Demo 1")
self.button1 = tk.Button(self, text = "Button 1", width = 25,
command = self.new_window)
self.button1.grid(row = 0, column = 1, columnspan = 2, sticky = tk.W+tk.E+tk.N+tk.S)

def new_window(self):
self.newWindow = Demo2()

class Demo2(tk.Frame):
def __init__(self):
new = tk.Frame.__init__(self)
new = tk.Toplevel(self)
new.title("Demo 2")
new.button = tk.Button(text = "Button 2", width = 25,
command = self.close_window)
new.button.pack()

def close_window(self):
self.destroy()

def main():
Demo1().mainloop()

if __name__ == '__main__':
main()

最佳答案

我以更有条理、更实用的方式重写了您的代码:

import tkinter as tk

class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()

def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)

class Demo2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
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()

结果:

Demo1 window Demo2 window

关于python - 用于多个窗口的 Tkinter 示例代码,为什么按钮无法正确加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115378/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com