Tom Fuller Tom Fuller - 3 months ago 19
Python Question

StringVar.set("...") does not work in multiple tkinter windows

My program has a library which opens a new window

This is the library (its called make_entry):

from tkinter import *

def Create():
Window = Tk() # window
Window.geometry("900x500+50+50") # heightxwidth+x+y

mainPanel = Canvas(Window, width = 900, height = 500) # main screen
mainPanel.pack()

anyvar = StringVar() # the text in the entry
entry = Entry(mainPanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainPanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")

Window.mainloop()

#Create()


If I run this library by itself then everything works fine, but when I import it from another program the only thing which doesn't work is
anyvar.set("This doesnt work!!!!!")
.

Here is where I import it: (most of this code is cut out)

from tkinter import *
Window = Tk()
import make_entry
make_entry.Create()
Window.mainloop()


Is there a way to fix this problem without removing any of the windows?

Answer

You have two instances of Tk() which confuses Tkinter. I am guessing that the StringVar() is going to the other (first) instance. Instead, pass the only instance to the function, and use a Toplevel for a new window.

from tkinter import *

def Create(root):
    window=Toplevel(root)    
    window.geometry("900x500+50+50") # heightxwidth+x+y

    mainpanel = Canvas(window, width = 900, height = 500) # main screen
    mainpanel.pack()

    anyvar = StringVar() # the text in the entry
    entry = Entry(mainpanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
    mainpanel.create_window(200, 100, window = entry)
    anyvar.set("This doesnt work!!!!!")

and

from tkinter import *
Window = Tk()
import make_entry
make_entry.Create(Window)
Window.mainloop()