Search code examples
pythontkintertkinter-button

Tkinter call up a function with a button or with a key


I need to create a function that starts when I press a botton of the GUI or when I press a key like ENTER. It's possible? I have created the single functions that perform one of these 2 cases, can I merge them? I am attaching the code for better understanding

LoginWindow = tk.Tk() #code of function with button
canvas = tk.Canvas(LoginWindow, width=480, height=120, bg='lightsteelblue2', relief='raised')
canvas.pack()
def getLogin():
    tk.messagebox.showinfo("Hello", "Hello")
LogButton = tk.Button(text="Login", command=getLogin, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas.create_window(240, 60, window=LogButton)

LoginWindow.mainloop()
####
####
LoginWindow = tk.Tk() #code of function with ENTER key
canvas = tk.Canvas(LoginWindow, width=480, height=120, bg='lightsteelblue2', relief='raised')
canvas.pack()
def getLogin(event):
    tk.messagebox.showinfo("Hello", "Hello")
LoginWindow.bind('<Return>', getLogin)

LoginWindow.mainloop()

there is a way to combine the 2 functions


Solution

  • You can change the function signature like this:

    def getLogin(event=None):
        tk.messagebox.showinfo("Hello", "Hello")
    

    Then the same function can be called in the two different cases.