Ive made a game where at the end of the game, I change the command that is called by the button.
I was wondering if there was a way to link the bind
to the button rather than the command, or if I could change the command called by the bind
.
Here is my code for the button:
# create the button
self.but = Button(win, text="Submit", command=lambda: self.check_input(win))
self.but.grid(row=10, column=2, columnspan=3, sticky="NEWS")
win.bind("<enter>", self.check_input(win))
# change the button command
self.but["command"] = lambda: self.next(win, self.game_init)
self.but["text"] = "PLAY AGAIN!"
If your function does not use Event
passed by tkinter when a widget is bind-ed, then it is fairly simple:
def check_input(self,win,event=None):
....
....
self.but = Button(win, text="Submit", command=lambda: self.check_input(win))
....
win.bind("<enter>", lambda e: self.check_input(win,e))
Though an easier and dynamic way to always follow the buttons command is(like jasonharper said) but you cannot use e
at all, even if triggered by the given event:
win.bind("<enter>", lambda e: self.but.invoke())
An example to account for using same function with bind
and command
of a button:
from tkinter import *
root = Tk()
def func(win,e=None):
if e is not None:
print(f'Triggered by the hitting the {e.keysym} key')
else:
print('Triggered by the pressing button')
but = Button(root,text='Click me',command=lambda: func(root))
but.pack()
root.bind('<Return>',lambda e: func(root,e))
root.mainloop()
Also a good time to mention, your event is wrong, either you meant '<Return>'
(enter key) or '<Enter>'
(when you enter the bounds of a widget with cursor)
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.