问题描述
限时送ChatGPT账号..我正在尝试一个程序,它将显示在输入框中输入的相应名称的标签.问题:它重叠并显示标签,而不是消失之前的条目标签.
I am trying a program,which will display label for the respective name entered in the Entry box. Problem: It overlaps and displays the label,instead of disappearing the previous entry label.
我的编码:
import Tkinter as tki
class App(object):
def __init__(self,root):
self.root = root
self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
button3.grid(column=0,row=2)
self.entry = tki.Entry(self.txt_frm)
self.entry.grid(column=1,row=0)
def retrieve_inpu(self):
ent = self.entry.get()
label = tki.Label(self.txt_frm,text=ent)
label.grid(column=0,row=3)
root = tki.Tk()
app = App(root)
root.mainloop()
请帮我删除之前的条目并显示标签.
Please help me to disappear the previous entry and display the label.
推荐答案
不是每次按下按钮时都创建一个新标签,只需更改标签的文本即可.我已经编辑了您的代码来演示:
Instead of creating a new label every time the button is pressed, just change the text of the label. I have edited your code to demonstrate:
import Tkinter as tki
class App(object):
def __init__(self,root):
self.root = root
self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
button3.grid(column=0,row=2)
self.entry = tki.Entry(self.txt_frm)
self.entry.grid(column=1,row=0)
#create label in init
self.label = tki.Label(self.txt_frm)
self.label.grid(column=0,row=3)
def retrieve_inpu(self):
ent = self.entry.get()
#treat label properties as a dict for tkinter
#assign a new text value
self.label['text'] = ent
root = tki.Tk()
app = App(root)
root.mainloop()
当然,如果您希望每次都创建一个新标签,请先销毁旧标签.这是对相同代码的不同修改.
Of course, if you prefer to create a new label every time, destroy the old one first. This is a different modification of the same code.
import Tkinter as tki
class App(object):
def __init__(self,root):
self.root = root
self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
button3.grid(column=0,row=2)
self.entry = tki.Entry(self.txt_frm)
self.entry.grid(column=1,row=0)
#place holder for label variable
self.label = None
def retrieve_inpu(self):
ent = self.entry.get()
#destroy the widget if it has been created
#you will have a bunch of orphans if you don't
if self.label:
self.label.destroy()
self.label = tki.Label(self.txt_frm,text=ent)
self.label.grid(column=0,row=3)
root = tki.Tk()
app = App(root)
root.mainloop()
这篇关于tkinter 显示当前标签,删除上一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论