tkinter显示当前标签,删除前一个标签

时间:2014-12-26 08:56:53

标签: python tkinter

我正在尝试一个程序,该程序将显示在“输入”框中输入的相应名称的标签。 问题:它重叠并显示标签,而不是消失之前的条目标签。

我的编码:

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

请帮我消失上一个条目并显示标签。

1 个答案:

答案 0 :(得分:3)

每次按下按钮时,只需更改标签的文本,而不是创建新标签。我已编辑您的代码以演示:

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

当然,如果您希望每次都创建一个新标签,请先破坏旧标签。这是对相同代码的不同修改。

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