Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Tkinter Entry not showing the current value of textvariable

Consider this code:

from tkinter import *
from tkinter.ttk import *

tk=Tk()

def sub():
    var=StringVar(value='default value')

    def f(): pass

    Entry(tk,textvariable=var).pack()
    Button(tk,text='OK',command=f).pack()

sub()
mainloop()

We expect the value of var appears in the entry, but actually it doesn't.

nothing in the entry

The weird thing is that if I put the statement var.get() in the callback function of the button, the value of var will apear.

the value appeared

Is that a bug caused by some kind of local variable optimization in Python? And what can I do to make sure that the value of textvariable will always appear in the entry?

Please execuse me for my poor English.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's getting garbage collected.

You can just get rid of the function (you also shouldn't nest functions like this)

from tkinter import *
from tkinter.ttk import *

tk=Tk()

var=StringVar(value="default value")
Entry(tk, textvariable=var).pack()
Button(tk,text='OK').pack()

mainloop()

Or, if you want to keep the function.. set the stringvar as an attribute of tk or make it global.

Making it global:

from tkinter import *
from tkinter.ttk import *

tk=Tk()
var = StringVar(value="Default value")

def sub():

    Entry(tk, textvariable=var).pack()
    Button(tk,text='OK').pack()

sub()
mainloop()

As an attribute of tk:

from tkinter import *
from tkinter.ttk import *

tk=Tk()

def sub():

    tk.var = StringVar(value="Default value")
    Entry(tk, textvariable=tk.var).pack()
    Button(tk,text='OK').pack()

sub()
mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...