删除标签文本并在单击按钮时设置新的标签文本 [英] Remove label text and set new label text on button click

查看:92
本文介绍了删除标签文本并在单击按钮时设置新的标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个较小的程序,以帮助排除主程序的故障.在此程序中,我希望在显示新标签文本之前删除先前的标签文本.这很重要,因为如果您将旧标签文本留在标签中,则文本最终会彼此重叠.

I have made a smaller program to help troubleshoot for the main program. In this program I want the previous label text to be deleted before the new label text is displayed. This is important because if you leave the old label text in the label, the text ends up overlaping eachother.

from tkinter import *

root = Tk()

root.geometry("400x200")

def onButtonClick():
    while True:
        answerLabel = Label(root, text=wordEntry.get())
        answerLabel.grid(row=1, column=1)
        break


enterWordLabel = Label(root, text="Enter a word")
enterWordLabel.grid(row=0, column=0)

wordEntry = Entry(root)
wordEntry.grid(row=0, column=1)

enterButton = Button(root, text="Enter", command=onButtonClick)
enterButton.grid(row=0, column=2)

root.mainloop()

推荐答案

每个小部件都有一个configure方法,可用于更改其属性.代码中的问题是您创建了新标签,而不是更改现有标签的文本.

Every widget has a configure method which allows you to change its attributes. The problem in your code is that you create new labels rather than changing the text of an existing label.

正确的解决方案是创建一次answerLabel,然后在脚本中调用configure方法:

The proper solution is to create answerLabel once, and then call the configure method in your script:

...
answerLabel = Label(root, text="")
answerLabel.grid(row=1, column=1)
...

def onButtonClick():
    answerLabel.configure(text=wordEntry.get())

这篇关于删除标签文本并在单击按钮时设置新的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆