Home > Blockchain >  How can I make this into one button?
How can I make this into one button?

Time:11-29

So, I'm trying to make it so if the entry field == the password (123), the button to proceed (enterbutton)'s state becomes active rather than disabled. I've only been able to somewhat accomplish this using 2 buttons, though if "123" is entered, and then removed the state of "enterbutton" does not change. How could I make this function all in the "enterbutton" rather than having to have 2 buttons, as well as making it update if said password is removed?

root = Tk()
root.geometry("500x300")


e = Entry(root)
e.insert(0, "Enter your password")

def check():
    password = e.get()
    if password == "123":
         enterbutton["state"] = ACTIVE
    if password != "123":
        enterbutton["state"] = DISABLED

button = Button(root, text="b", width=10, height=3, command=check)
enterbutton = Button(root, text="Enter", state=DISABLED, width=10, height=3,)

e.pack(pady=30)
enterbutton.pack()
button.pack()
mainloop()

CodePudding user response:

I suggest to use a StringVar for the entry field. Using its trace method, you can set a function that is called every time the text is changed. Also, I strongly recommend importing tkinter as tk instead of importing everyting with the * import.

import tkinter as tk

root = tk.Tk()
root.geometry("500x300")

var = tk.StringVar()
var.set("Enter your password")
e = tk.Entry(root, textvariable=var)

def check(*args):
    password = var.get()
    if password == '123':
        button['state'] = 'normal'
    else:
        button['state'] = 'disabled'
        
var.trace('w', check)

button = tk.Button(root, text="Enter", state='disabled', width=10, height=3,)

e.pack(pady=30)
button.pack()
root.mainloop()
  • Related