質問

I have a bit of difficulty with the code below. Basically, I want the code to, when I press the Enter button, to open the window2 but also close window1 simultaneously so that there is only one window and not two of them.

The code is...

from tkinter import *  

def window1():

    window = Tk()
    window.title("Welcome")

    f = Frame()
    f.pack()

    label1 = Label(window, text = "Welcome to the random window")
    label1.pack()

    button1 = Button(window, text = "Enter...", command = window2)
    button1.pack()

def window2():

    screen = Tk()
    screen.title("Pop-Up!")

    fr = Frame()
    fr.pack()

    label2 = Label(screen, text = "This is a pop-up screen!")
    label2.pack()

    button2 = Button(screen, text = "Return", command = window1)
    button2.pack()

window1()
役に立ちましたか?

解決

This is "Bad" because you're using two instances of Tk. Try instead using TopLevels.

import tkinter as tk

def window1():
    window = tk.Toplevel(root)
    window.title("Welcome")

    # etc etc ...

    tk.Button(window,text="Enter...",command=lambda: window2(window)).pack()

def window2(old_window):
    old_window.destroy()
    # window2 stuff

root = tk.Tk()
root.iconify() # to minimize it, since we're just using Toplevels on top of it
window1()
root.mainloop()

他のヒント

When you are using the Tk() function, you are creating a new instance of the Tcl/tkinter interpreter. Instead use Toplevel() which will make a new window in the current interpreter.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top