简体   繁体   中英

Tkinter - How can I open a window by clicking a button?

After my attempt in trying to make a game using EasyGUI, I found out that it won't do something that is important to the game so I started to use Tkinter instead. However I am running into another problem that I am not sure how to fix. Here's the code:

money = Button(box2, text = "Get Money", highlightbackground = "yellow", command = close_parentg)

def moneywindow():
    parent.destroy() # The button is inside the parent.
    Money.mainloop() # This is the window I want to open.

The destroy() command works fine, because when I press the button the first window closes, but if I run the program, the second window pops up even though I haven't told it to (or I at least think I haven't).

How can I stop the second window from popping up in the beginning and to only show up when I click the button?

mainloop() isn't what creates windows. The only two ways a window gets created is when you create an instance of Tk at the start of your program, and when you create instances of Toplevel while your program is running.

Your GUI should only ever call mainloop() exactly once, and it should stay running for the life of the application. It will exit when you destroy the root window, and tkinter is designed such that when you destroy the root window, the program exits.

Once you do that, no windows will pop up unless you explicitly create them with Toplevel .

Here's an example that lets you create multiple windows, and uses lambda to give each window a button that destroys itself.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        new_win_button = tk.Button(self, text="Create new window", 
                                   command=self.new_window)
        new_win_button.pack(side="top", padx=20, pady=20)

    def new_window(self):
        top = tk.Toplevel(self)
        label = tk.Label(top, text="Hello, world")
        b = tk.Button(top, text="Destroy me", 
                      command=lambda win=top: win.destroy())
        label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
        b.pack(side="bottom")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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