简体   繁体   English

按下按钮tkinter Python后打开一个新窗口

[英]Open a new window after pushing button tkinter Python

I would like to create a Button that open a new tkinter window when it is pushed. 我想创建一个按钮,当按下它时会打开一个新的tkinter窗口。 I have already found a solution in another post but in this example i would like to desactivate the button when a new window is open . 我已经在另一篇文章中找到了解决方案,但是在此示例中,我想在打开新窗口时取消激活按钮。 Here is what i have (test code) : 这是我所拥有的(测试代码):

import Tkinter as tk

def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

so i would like to desactivate the button b while a new window is still open. 因此,我想在一个新窗口仍处于打开状态时停用按钮b

Thanks. 谢谢。

There are a couple different ways that first come to mind. 首先想到几种不同的方法。

One way would be just to disable interaction with the entire window, this would be done by using the .grab_set() method on your newly created window. 一种方法是禁用与整个窗口的交互,这可以通过在新创建的窗口上使用.grab_set()方法来完成。

def create_window():
    window = tk.Toplevel(root)
    window.grab_set()

This method means the created window is now focused on, when the focused window is destroyed you will then again be able to interact with other windows. 此方法意味着现在将焦点集中在创建的窗口上,当聚焦的窗口被破坏时,您将可以再次与其他窗口进行交互。

Another way would be to have your function create_window() take the button as an input, then use the .configure(state="disabled") on the button 另一种方法是让函数create_window()将按钮作为输入,然后在按钮上使用.configure(state="disabled")

def create_window(button):
    window = tk.Toplevel(root)
    button.configure(state="disabled")

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=lambda: create_window(b))
b.pack()

Please note that since your function needs an input now, you need to use command= lambda:create_window(b) so then the create_window() isn't run when the button is created. 请注意,由于您的函数现在需要输入,因此您需要使用command= lambda:create_window(b)以便在创建按钮时不会运行create_window()

However now you would have to write another function that will change the buttons state back to .configure(state="normal") when the new window is destroyed. 但是,现在您必须编写另一个函数,以便在销毁新窗口时将按钮状态更改回.configure(state="normal") eg 例如

def create_window(button):
    window = tk.Toplevel(root)

    def on_close():
        button.configure(state="normal")
        window.destroy()

    button.configure(state="disabled")

    window.protocol("WM_DELETE_WINDOW", on_close)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM