Python2.7:更新Tkinter标签小部件内容

2024-04-18 19:14:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更新我的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()

我尝试了几种方法,但是要么标签不更新,要么解释器出错。 注意:在摘录中,我尽可能多地删除了代码,以避免混淆。在


Tags: 代码fromimportselfhttptkinterdefcolumn
1条回答
网友
1楼 · 发布于 2024-04-18 19:14:39

您需要使用StringVarset方法来更改标签文本。同时:

StatusTextVar = "Success"

不是引用self,也不会更改任何状态。在

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

^{pr2}$

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

正如人们所期望的那样。在

相关问题 更多 >