【发布时间】:2017-04-12 06:30:00
【问题描述】:
我正在尝试更新标签,但我编写的代码每次都会创建一个新标签。我对 tkinter 比较陌生,所以我不明白如何将其他答案应用于我的代码。
from tkinter import *
import random
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master=master
self.init_window()
def init_window(self):
self.pack(fill=BOTH, expand=1)
testButton=Button(self, text="Press", command=calc)
testButton.pack()
l1=Label(text="")
def testbutton(ans): #creates a new instance of l1 each time, I want to update existing l1
var=StringVar()
l1=Label(textvariable=var) #l1.configure() gives error l1 not defined
var.set(ans)
l1.pack()
def calc():
list1=["a","b","c"]
index=random.randint(0,2)
answer=list1[index]
Window.testbutton(answer)
root=Tk()
root.geometry("400x300")
app=Window(root)
root.mainloop()
每次按下按钮时,都会创建一个新标签,而不是更新现有标签上的文本。
这是我实际项目的简化版本,但突出了标签的问题。
我尝试在 testbutton 函数中使用l1.configure(...),但它运行一个错误,即 l1 未定义。
【问题讨论】:
标签: python python-3.x tkinter