python-3.x Tkinter -如何在窗口打开时禁用按钮

06odsfpq  于 2022-12-05  发布在  Python
关注(0)|答案(3)|浏览(266)

我是**'Tkinter'程式库的新手**,我想知道如何在开启新 windows 时停用按钮。例如,如果按一下主 windows 上的按钮,就会开启新 windows ,而且主 windows 上的所有按钮都会停用。 windows 关闭后,应该重新启用按钮。
下面是我的代码示例:

from tkinter import *

root = Tk()

def z():
    w = Toplevel()

    bu = Button(w, text = "Click!", font = 'bold')
    bu.pack()

b = Button(root, text = "Click!", command = z)
b.pack()

root.mainloop()

**Extra:**如果有人能告诉我如何在不关闭整个“Tkinter”程序的情况下关闭“root”窗口,我也会很感激。例如,如果第二个窗口是打开的,我希望能够关闭第一个窗口,或者至少最小化它。

cxfofazt

cxfofazt1#

You can hide window

root.withdraw()

# or 

root.iconify()

and show again

root.deiconify()

To disable button

b['state'] = 'disabled'

To enable button

b['state'] = 'normal'

EDIT: as @acw1668 noted in comment it needs win.protocol() to run close_second when user used closing button [X] on title bar

import tkinter as tk # PEP8: `import *` is not preferred

#--- functions ---

def close_second():
    win.destroy()

    b['state'] = 'normal'

    root.deiconify()

def open_second():
    global win

    b['state'] = 'disabled'
    #root.iconify()
    root.withdraw()

    win = tk.Toplevel()

    win_b = tk.Button(win, text="Close Second", command=close_second)
    win_b.pack()

    # run `close_second` when user used closing button [X] on title bar
    win.protocol("WM_DELETE_WINDOW", close_second)

# --- main ---

root = tk.Tk()

b = tk.Button(root, text="Open Second", command=open_second)
b.pack()

root.mainloop()
lsmepo6l

lsmepo6l2#

您可以使用.grab_set()来禁用与主窗口的交互。您可以在单击某个按钮时关闭该窗口,并在单击另一个按钮时重新打开上一个窗口。

from tkinter import *

root = Tk()

def reopen():
    root.mainloop()
    w.withdraw()

def z():
    w = Toplevel()
    w.grab_set()
    bu = Button(w, text = "Click!", font = 'bold', command=reopen)
    bu.pack()
    root.withdraw()
    w.mainloop()

b = Button(root, text = "Click!", command = z)
b.pack()

root.mainloop()
z2acfund

z2acfund3#

欢迎来到Tkinter图书馆。
我知道你为什么要用“w”,你可以用root,它就可以工作了。

from tkinter import *
root = Tk()

def z():

    bu = Button(root, text = "Click!", font = 'bold')
    bu.pack()

b = Button(root, text = "Click!", command = z)
b.pack()

root.mainloop()

如果你在python和tkinter中遇到任何问题,请询问我。

相关问题