简体   繁体   English

如何将事件正确绑定到我的按钮? 我的按钮似乎在点击之前执行了该功能

[英]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. 但是,一旦ui加载,事件似乎就会加载。 What am I doing wrong? 我究竟做错了什么?

From the code below, the click function doesn't load right when ui is loaded. 从下面的代码中,加载ui时,单击功能无法正确加载。 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) . 你需要self.button = Button(text="Send",width=8,command=clicky)

There's a difference between callbacks registered via command and callbacks registered via bind . 通过command注册的回调和通过bind注册的回调之间存在差异。 With command , the callback doesn't get passed any additional arguments. 使用command ,回调不会传递任何其他参数。 With bind , the callback gets passed an event object. 使用bind ,回调会传递一个事件对象。


Also, in case it wasn't clear, note that command is specific to Button objects whereas bind can be applied to any Tkinter widget. 此外,如果不清楚,请注意该command特定于Button对象,而bind可以应用于任何Tkinter小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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