Search code examples
pythonuser-interfacetkinter

Why using Tk() instead of Toplevel() for my 2nd window in Tkinter doesn't let me update a text variable in a label


I want to use Tk() for my new window, because I'm going to destroy the main one and let the second one run; however, when I use it, it doesn't let my label's textvariable updates, but with a simple change like using Toplevel() it works.

here is my code:


from tkinter import *
from tkinter import ttk

def fill(s,c):
    c += 1
    the_bar['value'] = c
    if c == 25:
        text.set('text 2')
    elif c == 50:
        text.set('text 3')
    elif c == 75:
        text.set('text 4')
    if c<=s:
        loading_window.after(50,fill,s,c)
    else:
        the_bar.destroy()
        loading_window.destroy()

def load():
    global loading_window
    loading_window = Tk()
    loading_window.title('loading')
    global text
    text = StringVar()
    text.set('text 1')
    txt = Label(loading_window,textvariable=text)
    txt.pack()
    global the_bar 
    the_bar = ttk.Progressbar(loading_window,length=300,orient=HORIZONTAL,maximum=100)
    the_bar.pack()
    delay, steps, count = 50,100,0
    loading_window.after(delay,fill,steps,count)
    loading_window.mainloop()
    
load() #this is within a button in my main Tk() window

Solution

  • You shouldn't create multiple instances of Tk(), this explains why. Basically the tk.StringVar that you create is bound to the first instance of Tk() and it's not accessible from the other window. If you want to hide the root window you can call root.withdraw() and use toplevel() for the other window.