问题描述
限时送ChatGPT账号..我想知道是否有办法打开 Toplevel() 的新实例并通过按下按钮关闭当前实例,即关闭当前窗口并打开一个新窗口.这是有问题的代码:
def start(self):self.name = tk.DoubleVar()name_w = tk.Toplevel(root)name_w.wm_title("输入姓名")f1 = tk.Frame(name_w)f1.pack()L1 = tk.Label(f1, text="请输入您的姓名!")L1.grid(行=0,列=0)E1 = tk.Entry(f1, textvariable=self.name)E1.grid(行=1,列=0)N1 = tk.Button(f1, text="Next", command = self.Q1)N1.grid(行=2,列=0)
在这种情况下,我希望调用 self.Q1,同时销毁 name_w.有没有办法做到这一点?谢谢.
解决方案是的,这是可能的.要关闭 Toplevel
的实例,只需将其销毁即可.您需要保存对窗口的引用.在你的情况下,我要么让 Q1
销毁窗口,要么创建一个单独的函数来调用 Q1
然后销毁窗口.这完全取决于Q1
的主要目的是什么.
例如:
def start(self):...self.new_window = name_w...def quit_window(self):self.Q1()self.new_window.destroy()
如果您有多个这些,您可能需要将窗口引用存储在列表或字典中,但基本机制是相同的:使用 .destroy()
销毁窗口.>
当然,这不是唯一的方法.您可以使用 lambda 或 functools.partial
以及一个接受要销毁的窗口名称的函数,或者您可以使用嵌套函数等.
I was wondering if there was a way to open a new instance of Toplevel() and close the current one via the press of a button, i.e. close the current window and open a new one. Here is the code in question:
def start(self):
self.name = tk.DoubleVar()
name_w = tk.Toplevel(root)
name_w.wm_title("Enter name")
f1 = tk.Frame(name_w)
f1.pack()
L1 = tk.Label(f1, text="Please enter your name!")
L1.grid(row=0, column=0)
E1 = tk.Entry(f1, textvariable=self.name)
E1.grid(row=1, column=0)
N1 = tk.Button(f1, text="Next", command = self.Q1)
N1.grid(row=2, column=0)
In this case, I want self.Q1 to be called, while also destroying name_w. Is there anyway to do this? Thanks.
解决方案Yes, it's possible. To close an instance of Toplevel
simply destroy it. You'll need to save a reference to the window. In your case I would either have Q1
destroy the window, or make a separate function that calls Q1
and then destroys the window. It all depends on what the main purpose of Q1
is.
For example:
def start(self):
...
self.new_window = name_w
...
def quit_window(self):
self.Q1()
self.new_window.destroy()
If you have multiple of these you might need to store the window references in a list or dictionary, but the basic mechanism is the same: use .destroy()
to destroy the window.
This isn't the only way, of course. You could use lambda or functools.partial
and a function that accepts the name of the window to destroy, or you could use nested functions, etc.
这篇关于通过 Tkinter 中的按钮关闭窗口并打开一个新窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论