Toaster
Toaster

Reputation: 87

How do I open multiple Tk() windows at the same time?

My problem is simple, but i really don't know what the issue is. I'm trying to open more than one window almost at the same time, but if i do it like that:

from tkinter import *
import threading
import time

class new_window:
    def build(self, killtime):
        self.w = Tk()
        self.w.update()
        time.sleep(killtime)
        self.w.destroy()
    def __init__(self, killtime):
        threading.Thread(target=self.build(killtime)).start()

a = new_window(2)
time.sleep(2)
b = new_window(2)

it doesn't behave like: "open, wait, open" but instead like: "open, wait until killed, wait, open"

What i mean is that the delay starts after the first window is closed, not after the window started. I thought a Thread would help me out, but it didn't.

Hopefully one of you knows how to fix that.

Upvotes: 1

Views: 1553

Answers (2)

Toaster
Toaster

Reputation: 87

I did it like this now. But i still marked the Answer of @TheMaker as the Solution, cause its more compact and easier to understand.

from tkinter import *
import threading
import time
from random import *

root = Tk()
root.configure(background='black')

root.attributes("-fullscreen", True)

class new_window:
    def build(self, delay, x, y):
        self.w = Tk()
        self.w.title("")
        self.ws = root.winfo_screenwidth() # width of the screen
        self.hs = root.winfo_screenheight() # height of the screen
        self.w.geometry(f"250x100+{int(round(self.ws/100*x))}+{int(round(self.hs/100*y))}")
        self.w.update()
        time.sleep(delay)
    def __init__(self, delay, x, y):
        threading.Thread(target=self.build(delay, x, y)).start()

def rdm(delay, count):  
    i = 1
    while i<=count:
        new_window(delay, randint(1, 100), randint(1, 100))
        i+=1
rdm(0.02, 100)

root.mainloop()

Upvotes: 0

10 Rep
10 Rep

Reputation: 2270

You don't really need to use the threading module.

You can use the .after() method to open a new window a little after.

Here is your code:

from tkinter import *
window = Tk()
window.title("window1")
def open_new_window():
    window2 = Toplevel()
    window2.title("Window2")
window.after(1000, open_new_window)
window.mainloop()

Hope this helps!

Edit: The code above opens one window, then stops doing anything. If you want new windows to keep opening with a small delay in between, you can use the below code:

from tkinter import *
window = Tk()
window.title("window1")
def open_new_window():
    window2 = Toplevel()
    window2.title("Window2")

    window.after(1000, open_new_window)
open_new_window()

window.mainloop()

Hope this helps!

Upvotes: 2

Related Questions