使按钮一次只打开一个窗口(通过关闭顶层窗口启用按钮)

编程入门 行业动态 更新时间:2024-10-27 01:31:07
本文介绍了使按钮一次只打开一个窗口(通过关闭顶层窗口启用按钮)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 07:34:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391325.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   窗口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!