Python 2.7:更新Tkinter Label小部件内容

时间:2014-08-04 13:51:42

标签: python python-2.7 tkinter

我正在尝试让我的Tkinter Label小部件更新,但是,我觉得它很简单,现在我无法解决它。

我的代码是:

import Tkinter as tk
import json, htmllib, formatter, urllib2
from http_dict import http_status_dict
from urllib2 import *
from contextlib import closing  

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master) 
        self.grid() 
        self.createWidgets()

    def createWidgets(self):
        StatusTextVar = tk.StringVar()
        self.EntryText = tk.Entry(self)
        self.GetButton = tk.Button(self, command=self.GetURL)
        self.StatusLabel = tk.Label(self, textvariable=StatusTextVar)

        self.EntryText.grid(row=0, column=0)
        self.GetButton.grid(row=0, column=1, sticky=tk.E)
        self.StatusLabel.grid(row=1, column=0, sticky=tk.W)

    def GetURL(self):
         try:
             self.url_target = ("http://www." + self.EntryText.get())
             self.req = urllib2.urlopen(self.url_target)
             StatusTextVar = "Success"

         except:
             self.StatusTextVar = "Wrong input. Retry"
             pass

app = Application()   
app.mainloop()

我尝试了几种方法但是Label不会更新,或者解释器会引发错误。 注意:在摘录中,尽可能删除代码以避免混淆。

1 个答案:

答案 0 :(得分:2)

您需要使用StringVar set方法更改标签文字。也:

StatusTextVar = "Success"

不引用自我,也不会改变任何状态。

您应首先将所有StatusTextVar更改为self.StatusTextVar,然后更新设置的调用:

self.StatusTextVar = "Success"
self.StatusTextVar = "Wrong input. Retry"

self.StatusTextVar.set("Success")
self.StatusTextVar.set("Wrong input. Retry")

更新所有StatusTextVar个实例并使用set方法,我得到:

import Tkinter as tk
import json, htmllib, formatter, urllib2
from urllib2 import *
from contextlib import closing

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.StatusTextVar = tk.StringVar()
        self.EntryText = tk.Entry(self)
        self.GetButton = tk.Button(self, command=self.GetURL)
        self.StatusLabel = tk.Label(self, textvariable=self.StatusTextVar)

        self.EntryText.grid(row=0, column=0)
        self.GetButton.grid(row=0, column=1, sticky=tk.E)
        self.StatusLabel.grid(row=1, column=0, sticky=tk.W)

    def GetURL(self):
         try:
             self.url_target = ("http://www." + self.EntryText.get())
             self.req = urllib2.urlopen(self.url_target)
             self.StatusTextVar.set("Success")

         except:
             self.StatusTextVar.set("Wrong input. Retry")
             pass

root = tk.Tk()
app = Application(master=root)
app.mainloop()

它可以像人们期望的那样工作。