问题描述
限时送ChatGPT账号..我希望 NewWinButton
一次只创建一个新窗口,这意味着如果
I want NewWinButton
to create only one new window at a time, which means if
if NewWin.winfo_exists() == 1:
NewWinButton.config(state='disabled')
else:
NewWinButton.config(state='normal')
如果我向新窗口添加一个按钮(在本例中为QuitButton
),我就可以完成这项工作:
I can make this work if I add a button to the new window (QuitButton
in this example):
import tkinter as tk
root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')
def get_new_win():
NewWin = tk.Toplevel(root)
NewWin.title('New Window')
NewWin.geometry('300x300')
NewWinButton.config(state='disable')
def quit_win():
NewWin.destroy()
NewWinButton.config(state='normal')
QuitButton = tk.Button(NewWin,text='Quit', command=quit_win).pack()
NewWinButton = tk.Button(root,text='New Window', get_new_win).pack()
root.mainloop()
当且仅当我使用 QuitButton
关闭新窗口时才有效;但是,如果我在新窗口中使用关闭按钮,那么 NewWinButton 将保持禁用"状态.
This works if and only if I use QuitButton
to close the new window; however, if I use the close button in the new window, then the NewWinButton will remain 'disabled'.
谁能告诉我如何解决这个问题?
Can anyone tell me how to fix this?
推荐答案
使用 NewWin.protocol("WM_DELETE_WINDOW", quit_win)
将函数 quit_win
分配给关闭按钮.
Use NewWin.protocol("WM_DELETE_WINDOW", quit_win)
to assign function quit_win
to the close button.
import tkinter as tk
root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')
def get_new_win():
NewWin = tk.Toplevel(root)
NewWin.title('New Window')
NewWin.geometry('300x300')
NewWinButton.config(state='disable')
def quit_win():
NewWin.destroy()
NewWinButton.config(state='normal')
QuitButton = tk.Button(NewWin, text='Quit', command=quit_win)
QuitButton.pack()
NewWin.protocol("WM_DELETE_WINDOW", quit_win)
NewWinButton = tk.Button(root, text='New Window', command=get_new_win)
NewWinButton.pack()
root.mainloop()
<小时>
顺便说一句:
BTW:
pack()
方法返回 None
,而不是按钮实例:
The pack()
method returns None
, not a button instance:
NewWinButton = tk.Button(...).pack()
使用这个:
NewWinButton = tk.Button(...)
NewWinButton.pack()
这篇关于使按钮一次只打开一个窗口(通过关闭顶层窗口启用按钮)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论