Tkinter Entry not showing the current value of textvariable

主宰稳场 提交于 2019-11-28 10:07:02

问题


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.

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.

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.


回答1:


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()


来源:https://stackoverflow.com/questions/37350971/tkinter-entry-not-showing-the-current-value-of-textvariable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!