How to create a Reset button using Tkinter

时间:2019-04-14 16:09:34

标签: tkinter

I am trying to create a reset button that allows me to reset username details if clicked. How can I achieve this please?

I have tried different methods but I get

Name Error: enter name is not defined

main_window_page = Tk()
main_window_page.title("GA")
main_window_page.geometry("600x600")

entername = StringVar()
enterpassword = StringVar()

Username=tk.Label(text="Username")
Username.pack(pady=1,padx=1)
EnterName=tk.Entry(bd=4,textvariable=entername)
EnterName.pack(pady=5,padx=5)

Reset=tk.Button(text="Reset",command=clearFunc)
Reset.pack(pady=13,padx=13)

main_window_page.mainloop()

def clearFunc():
  entername.set("0")

1 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出Tobi。

您需要将entername设为全局字符串变量,以便可以在clearFunc子例程中对其进行引用/使用。

global entername

要使clearFunc()将entername的值设置为空,必须将entername的值设置为“”:

entername.set("")

此外,请始终将mainloop放在代码的末尾。

在引用它之前,您还需要定义clearFunc子例程,因此我将其移到了reset按钮之前。

代码:

main_window_page = Tk()
main_window_page.title("GA")
main_window_page.geometry("600x600")

global entername #make it a global string variable
entername = StringVar()
enterpassword = StringVar()

Username=tk.Label(text="Username")
Username.pack(pady=1,padx=1)
EnterName=tk.Entry(bd=4,textvariable=entername)
EnterName.pack(pady=5,padx=5)

def clearFunc():
    entername.set("")

Reset=tk.Button(text="Reset",command=clearFunc)
Reset.pack(pady=13,padx=13)

main_window_page.mainloop()