这是一个非常简单的 Python Tk 程序。我似乎无法阻止一个简单的问题,我确信我错过了一些简单的事情。
我做一个标签:
myLabelText = StringVar()
myLabelText.set("Something kinda long")
myLabel = Label(frame, textvariable=myLabelText).pack()
稍后在同一程序中,我想更新该标签以显示“Foo”...
myLabelText.set("Foo")
frame.update_idletasks()
标签现在看起来像“Fooething kinda long” 目标是只有“Foo”并清除标签文本的其余部分。
我试图将标签设置为一长串空格,但由于某种原因,这并没有清除该字段中的文本。这样做的正确方法是什么?
编辑
这是一个演示我的问题的完整示例。
from Tkinter import *
import tkFileDialog, Tkconstants
import time
import urllib2
def main():
" Controlling function "
root = Tk()
app = App(root)
root.mainloop()
class App:
" Class for this application "
def __init__(self, master):
# Setup the window
frame = Frame(master, width=400, height=200)
frame.pack()
frame.pack_propagate(0)
self.frame = frame
self.master = master
# Start Button
self.button = Button(frame, text='Start', bg="#339933", height=3, width=10, command=self.start)
self.button.pack()
# Label
self.operation_action_text = StringVar()
self.operation_action_text.set("Waiting on user to click start...")
self.operation_action = Label(frame, textvariable=self.operation_action_text)
self.operation_action.pack()
def start(self):
" Change the label "
# Do something and tell the user
response = urllib2.urlopen('http://www.kennypyatt.com')
json_string = response.read()
self.operation_action_text.set("Something kinda long")
self.frame.update_idletasks()
time.sleep(2)
# Do something else and tell the user
response = urllib2.urlopen('http://www.kennypyatt.com')
json_string = response.read()
self.operation_action_text.set("ABCDEFGHI")
self.frame.update_idletasks()
time.sleep(2)
# Do a third thing and tell the user
response = urllib2.urlopen('http://www.kennypyatt.com')
json_string = response.read()
self.operation_action_text.set("FOO")
self.frame.update_idletasks()
return
main()