doglas doglas - 1 month ago 10
Python Question

Python + Tkinter: How to open two independent windows from two subfunctions?

I want to have the two windows from the two subfunctions opened together, when the programm is run.

(Well, to be more exactly, the two subfunctions dont run together. But as a result, I want to have two windows shown.)

But my following code only allows me to open one window at the same time.

I would prefer to have the two-subfunctions-structure. So how can I change the code? Thanks for your help!

from Tkinter import *

def Window1():
root1 = Tk()
root1.title("Window 1")

Label1 = Label(root1,text="abc",width=60)
Label1.grid(row=0, column=0)

root1.mainloop()


def Window2():
root2 = Tk()
root2.title("Window 2")

Label2 = Label(root2,text="ABC" ,width=60)
Label2.grid(row=0, column=0)

root2.mainloop()

Window1()
Window2()

Answer

If you are opening more than one windows, you should make any windows after the first an instance of a Toplevel widget.

The below example shows how this could be done. The first windows is the main one and will kill the app if its closed. The second windows will not kill the app but will just close itself.

from Tkinter import *

def mainwindow(root):
    root.title("Window 1")
    Label1 = Label(root,text="abc",width=60)
    Label1.grid(row=0, column=0)


def otherwindow(parent):
    root2 = Toplevel(parent)
    root2.title("Window 2")

    Label2 = Label(root2,text="ABC" ,width=60)
    Label2.grid(row=0, column=0)

root = Tk()

mainwindow(root)
otherwindow(root)

root.mainloop()