简体   繁体   中英

String Variable not setting initial value

class Lay():
  def __init__(self):
    root=Tk()
    root.configure(background="black")
    var=StringVar()
    var.set("OVERVIEW")
    Label(root,textvariable=var).grid(row=1,column=1,sticky=W+E+N+S)
    Entry(root, textvariable = var).place(rely=1.0,relx=1.0,x=0,y=0,anchor=SE)
    root.mainloop() 

Hello, when i run this the initial value of the string variable does not appear, but when i type into the entry box, the text i type appears in the label. I'm not quite sure why this occurs, but i get an empty label to begin with, with the entry box. Thank you for any help.

Although, I couldn't reproduce the problem, I refactored your code to initialize tkinter widgets through a class(inspired by the snippet in the docs ) and also increased the window size so that the widgets are clearly viewed. If there is anything else in your code that is calling multiple windows as @jasonharper suggested, you should share that.

import tkinter as tk

class Lay(tk.Tk):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master        
        self.var=tk.StringVar()
        self.var.set("OVERVIEW")        
        self.Widgets()   


    def Widgets(self):        
        self.displaylbl = tk.Label(self,textvariable=self.var)
        self.displaylbl.grid(row=2,column=1,sticky=tk.W+tk.E+tk.N+tk.S)        
        self.entry = tk.Entry(self, textvariable = self.var)
        self.entry.place(rely=1.0,relx=1.0,x=0,y=0,anchor=tk.SE)


app = Lay()
app.geometry("200x200")
app.mainloop()

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM