TKInter无法更改stringvar的值

时间:2015-09-02 16:49:25

标签: python tkinter

我有这个python 2.7.9代码。错误在于chooseKid()函数。 StringVar current和标签chosenKid不会更新。我已验证chooseKid()确实已运行,并且choice变量已设置。但是chosenKid

from Tkinter import Tk,Button,StringVar,Entry,Label
import random

root= Tk()

current=StringVar()
kids=[]

addKidName=Entry(root)
def addkid():
    kids.append(addKidName.get())
    print kids
addKid=Button(root, text="Add a student", command=addkid)


def choosekid():
    chosen=random.choice(kids)
    current.set(chosen)
chooseKid=Button(root,text="Pick random student", command=choosekid)
chosenKid=Label(root,text=current)


addKid.grid(row=0,column=1)
addKidName.grid(row=0,column=0)
chooseKid.grid(row=1,column=1)
chosenKid.grid(row=1,column=0)

root.mainloop()

1 个答案:

答案 0 :(得分:2)

您需要设置textvariable,而不是text。这将允许Label内容与StringVar中当前的内容相匹配。

chosenKid=Label(root, textvariable=current)