How to clear the Entry widget after a button is pressed in Tkinter?

后端 未结 11 1075
渐次进展
渐次进展 2020-12-01 10:44

I\'m trying to clear the Entry widget after the user presses a button using Tkinter.

I tried using ent.delete(0, END), but I got an error

相关标签:
11条回答
  • 2020-12-01 11:03

    real gets the value ent.get() which is just a string. It has no idea where it came from, and no way to affect the widget.

    Instead of real.delete(), call .delete() on the entry widget itself:

    def res(ent, real, secret):
        if secret == eval(real):
            showinfo(message='that is right!')
        ent.delete(0, END)
    
    def guess():
        ...
        btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))
    
    0 讨论(0)
  • 2020-12-01 11:03

    If in case you are using Python 3.x, you have to use

    txt_entry = Entry(root)

    txt_entry.pack()

    txt_entry.delete(0, tkinter.END)

    0 讨论(0)
  • 2020-12-01 11:09

    After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

    import tkinter as tk
    
    class App(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master, height=42, width=42)
            self.entry = tk.Entry(self)
            self.entry.focus()
            self.entry.pack()
            self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
            self.clear_button.pack()
    
        def clear_text(self):
            self.entry.delete(0, 'end')
    
    def main():
        root = tk.Tk()
        App(root).pack(expand=True, fill='both')
        root.mainloop()
    
    if __name__ == "__main__":
        main()
    
    0 讨论(0)
  • 2020-12-01 11:10

    You shall proceed with ent.delete(0,"end") instead of using 'END', use 'end' inside quotation.

     secret = randrange(1,100)
    print(secret)
    def res(real, secret):
        if secret==eval(real):
            showinfo(message='that is right!')
        real.delete(0, END)
    
    def guess():
        ge = Tk()
        ge.title('guessing game')
    
        Label(ge, text="what is your guess:").pack(side=TOP)
    
        ent = Entry(ge)
        ent.pack(side=TOP)
    
        btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
        btn.pack(side=LEFT)
    
        ge.mainloop()
    

    This shall solve your problem

    0 讨论(0)
  • 2020-12-01 11:14

    First of all, make sure the Text is enabled, then delete your tags, and then the content.

    myText.config(state=NORMAL)
    myText.tag_delete ("myTags")
    myText.delete(1.0, END)
    

    When the Text is "DISABLE", the delete does not work because the Text field is in read-only mode.

    0 讨论(0)
提交回复
热议问题