[英]Python 2.7: updating Tkinter Label widget content
我正在嘗試更新Tkinter標簽窗口小部件,但是,在我認為這很簡單的地方,現在我無法對其進行整理。
我的代碼是:
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不會更新,或者解釋器會引發錯誤。 注意:在摘錄中,我刪除了盡可能多的代碼以避免混淆。
您需要使用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()
正如人們所期望的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.