Jhonatan Zu
Jhonatan Zu

Reputation: 169

Tkinter textvariable does not work in a secondary window?

Because when I use textvariable from a secondary window called from a command in another window the variable.set () is not reflected in that secondary window.

example:

import tkinter as tk

def test():
    ven=tk.Tk()
    v1=tk.StringVar()
    v1.set('TEST')
    print(v1.get())
    tk.Label(ven, textvariable=v1).pack()
    ven.mainloop()

win=tk.Tk()
tk.Button(text='BOTON',command=test).pack()
win.mainloop()

In this case the message 'TEST' set through 'set' is not registered in the Label textvariable..

Why does this happen?

Upvotes: 1

Views: 155

Answers (1)

j_4321
j_4321

Reputation: 16169

Your problem comes from the fact that you have several Tk instances running simultaneously. Tkinter is based on the the Tk gui framework which is a tcl library. Therefore each Tk instance is not just a window, it's also a tcl interpreter, therefore, when you have several Tk instances, they cannot share StrinVar because the value of the StrinVar is defined in one interpreter (here win) which does not communicate with the other one (ven).

To avoid this kind of issue, just don't use several Tk instances, use Toplevel windows instead:

import tkinter as tk

def test():
    ven = tk.Toplevel(win)
    v1 = tk.StringVar(win)
    v1.set('TEST')
    print(v1.get())
    tk.Label(ven, textvariable=v1).pack()


win = tk.Tk()
tk.Button(text='BOTON', command=test).pack()
win.mainloop()

Upvotes: 1

Related Questions