简体   繁体   中英

How to properly bind an event to my button? My button seems to exe the function before click

I'm looking at the example codes online, seems like I'm doing exactly like them. But the event seems to load as soon as the ui loads. What am I doing wrong?

From the code below, the click function doesn't load right when ui is loaded. But when I click the button, it throws:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
TypeError: clicky() takes no arguments (1 given)

class LogIn:
    def __init__(self):
        self.root = Tk();
        self.root.title("480 - Chat Project Login");
        self.root.geometry("275x125");
        self.username = Label(self.root, text="Username: ");
        self.username.pack(side=LEFT);
        self.username.place(x=40, y=20);
        self.u_entry = Entry(self.root, width=20);
        self.u_entry.pack(side=RIGHT, ipady=4, ipadx=4);
        self.u_entry.place(x=110, y=20);
        self.password= Label(self.root, text="Password: ");
        self.password.pack(side=LEFT);
        self.password.place(x=40, y=50);
        self.p_entry = Entry(self.root, width=20);
        self.p_entry.pack(side=RIGHT, ipady=4, ipadx=4);
        self.p_entry.place(x=110, y=50);
        self.button = Button(text="Send", width=8);
        self.button.pack(side=RIGHT, ipady=4, ipadx=4);
        self.button.place(x=168, y=80);
        self.button.bind("<Button-1>", clicky);
        self.root.mainloop();

def clicky():
    print "hello";

if __name__ == "__main__":
    LogIn();
#    Client();

You need self.button = Button(text="Send",width=8,command=clicky) .

There's a difference between callbacks registered via command and callbacks registered via bind . With command , the callback doesn't get passed any additional arguments. With bind , the callback gets passed an event object.


Also, in case it wasn't clear, note that command is specific to Button objects whereas bind can be applied to any Tkinter widget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM