Python tkinter открывает одно окно вместо двух

Я работаю над графическим интерфейсом, используя tkinter. У меня появилось главное меню и внутри этого меню три кнопки. Я хотел бы открыть новое окно, нажав кнопку 3. В моем коде теперь он делает то, что я почти хочу. НО, как видите, я добавил к кнопке 3 команду уничтожить основной корень, чтобы перейти ко второму. Но это вызовет проблемы, например: когда я хочу закрыть главное меню, оно автоматически откроет второй корень. Я просто пытался проявить творческий подход, потому что не мог найти другого выхода, чтобы открыть новое окно с другим фоновым изображением. Любые идеи, трюки или функции, которые я мог бы использовать, чтобы сделать жизнь проще? мой код:

from tkinter import *
from tkinter.messagebox import showinfo


def clicked1():
    bericht = 'Deze functie is uitgeschakeld.'
    showinfo(title='popup', message=bericht)

root = Tk()

def quit():
    root.destroy()

a = root.wm_attributes('-fullscreen', 1)
#full screen


#w, h = root.winfo_screenwidth(), root.winfo_screenheight()
#root.geometry("%dx%d+0+0" % (w, h))


#Hoofdmenu achtergrond
C = Canvas(root, bg="blue", height=250, width=300)
filename = PhotoImage(file="C:\\Users\\Downloads\\test1.png")
background_label = Label(root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()


# Geen OV-chipkaart button
b=Button(master=root, command=clicked1)
photo=PhotoImage(file="C:\\Users\\Downloads\\button1.png")
b.config(image=photo,width="136",height="53", background='black')
b.place(x=310, y=340)

#exit button
exitbut = PhotoImage(file = "C:\\Users\\Downloads\\exit1.png")
starter = Label(image = exitbut)
starter.pack()

start = Label(image = exitbut)
start.place(x=900, y=140)

#Buitenland button
b2=Button(master=root, command=clicked1)
photo1=PhotoImage(file="C:\\Users\\Downloads\\button2.png")
b2.config(image=photo1,width="136",height="53", background='black')
b2.place(x=490, y=340)

#Reis informatie
b3=Button(master=root, command=quit)
photo2=PhotoImage(file="C:\\Users\\Downloads\\button3.png")
b3.config(image=photo2,width="136",height="53", background='black')
b3.place(x=680, y=340)


root.mainloop()


#2e window-------------------------------------------------------------
root2 = Tk()

#full screen
a = root2.wm_attributes('-fullscreen', 1)

#achtergrond
D = Canvas(root2, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\Downloads\\leeg.png")
background_label = Label(root2, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
D.pack()

# Geen OV-chipkaart button
c1=Button(master=root2, command=clicked1)
photo3=PhotoImage(file="C:\\Users\\Downloads\\mijnlocatie.png")
c1.config(image=photo3,width="136",height="53", background='black')
c1.place(x=210, y=70)

# Geen OV-chipkaart button
c2=Button(master=root2, command=clicked1)
photo4=PhotoImage(file="C:\\Users\\Downloads\\overigelocaties.png")
c2.config(image=photo4,width="136",height="53", background='black')
c2.place(x=210, y=140)


root2.mainloop()

person J. Adam    schedule 22.10.2017    source источник


Ответы (2)


У вас действительно не должно быть двух экземпляров Tk. tkinter не предназначен для такой работы. Если вы хотите другое окно поверх корневого, используйте Toplevel. Кроме того, я предлагаю вам придерживаться ООП-подхода и хранить окна как отдельные классы. Например:

import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.create_widgets()

    def create_widgets(self):
        """
        Instantiating all root window widgets
        """
        tk.Button(self, text='Open another window', command=self.open_dialog).pack()

    def open_dialog(self):
        d = Dialog(self)
        d.wait_window()

class Dialog(tk.Toplevel):

    def __init__(self, parent):
        super().__init__(parent)
        self.create_widgets()

    def create_widgets(self):
        """
        Instantiating all toplevel window widgets
        """
        tk.Label(self, text='Welcome to another window!').pack(padx=20, pady=50)

if __name__ == '__main__':
    app = App()
    app.mainloop()
person adder    schedule 22.10.2017

Это решит вашу проблему, используя Toplevel вместо вызова двух экземпляров Tk. Вы можете добавить свой полноэкранный атрибут и изображения, если сделаете это таким образом. Toplevel означает подчиненное окно для корневого окна, поэтому, если вы закроете корневое окно, оно закроет Toplevelокно для . Я изменил вашу quitфункцию на quit_window, так как вы также можете root.quit() закрыть окно.

from tkinter import *


def slave1():
    tp = Toplevel()
    tp.geometry("400x400")
    b = Button(tp, text="button") # you can add you image to it using photoimage
    b.place(x=200, y=200)


def quit_root():
    root.destroy()



root = Tk()
root.geometry("500x500")

button1 = Button(root, text="button one", command=slave1)
button2 = Button(root, text="button two")
button3 = Button(root, text="button three", command=quit_root)

button1.place(x=210, y=340)
button2.place(x=340, y=370)
button3.place(x=370, y=420)

root.mainloop()
person AD WAN    schedule 23.10.2017