此代码打开一个按钮,该按钮链接到另一个按钮。另一个按钮可以关闭它自己,但是第一个按钮不能自动关闭并同时打开一个新按钮,我该如何解决这个问题?
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.HelloButton = tk.Button(self.frame, text = 'Hello', width = 25, command = self.new_window,)
self.HelloButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
self.new_window
def new_window(self):
self.new_window = tk.Toplevel(self.master)
self.app = Demo2(self.new_window)
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()
答案 0 :(得分:2)
尝试重新定义Demo1.new_window()
,如下所示:
def new_window(self):
self.master.destroy() # close the current window
self.master = tk.Tk() # create another Tk instance
self.app = Demo2(self.master) # create Demo2 window
self.master.mainloop()
答案 1 :(得分:-1)
试试这个:
import tkinter as tk
class windowclass():
def __init__(self, master):
self.master = master
self.btn = tk.Button(master, text="Button", command=self.command)
self.btn.pack()
def command(self):
self.master.withdraw()
toplevel = tk.Toplevel(self.master)
toplevel.geometry("350x350")
app = Demo2(toplevel)
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()
root = tk.Tk()
root.title("window")
root.geometry("350x350")
cls = windowclass(root)
root.mainloop()
或者有时候,你想做别的事情,你可以隐藏它。
def __init__(self, parent):
self.root = parent
self.root.title("Main")
self.frame = Tk.Frame(parent)
self.frame.pack()
btn = Tk.Button(self.frame, text="New", command=self.openFrame)
btn.pack()
def hide(self):
self.root.withdraw()
def openFrame(self):
self.hide()
otherFrame = Tk.Toplevel()
otherFrame.geometry("400x300")
handler = lambda: self.CloseOtherFrame(otherFrame)
btn = Tk.Button(otherFrame, text="Close", command=handler)
btn.pack()
def CloseOtherFrame(self, otherFrame):
otherFrame.destroy()
self.show()