一个按钮和一个键试图同时执行一个功能

A button and a key trying to execute both a function

我有这个程序,为了输入信息,您可以按“按钮 1”Ingresa 或直接按 Enter。 我遇到的问题是,为了将键“”绑定到函数“cantidad_items”,我必须处理一个会破坏按钮 1 的事件。 我该如何解决这个问题,以便两种选择都可行?

from tkinter import *
import random
import webbrowser

#cantidad de items (el event activa el Enter)
def cantidad_items(event):
    
    global x
    
    x= int(texto1.get())
    texto1.delete(0, END)
    
    texto1.bind("<Return>",añadir)
    label1.configure(text = "Ingrese el título de los ítems")
    boton1.configure(text = "Ingresar", command=añadir)
    
#nombre de los items e impresión
def añadir(event = None): #No entiendo, explicación: bind() runs with argument, command= runs without argument

    new=2
    tabUrl = "http://google.com/?#q="
    item = texto1.get()
    lista.append(item)
    texto1.delete(0, END)
    
    if len(lista)== x:
        texto1.destroy()
        boton1.destroy()
        label1.destroy()
        rando = random.choice(lista)
        if ("coger" in lista):
            resultado = Label(window, text="Toca coger", font= "Helvetica 30")
            resultado.place(relx=0.5, rely=0.5, anchor= CENTER)
        elif ("Coger" in lista):
            resultado = Label(window, text="Toca coger", font= "Helvetica 30")
            resultado.place(relx=0.5, rely=0.5, anchor= CENTER)
        else:
            webbrowser.open(tabUrl + rando, new=new)

            
## Revisar bug con ingresar()----------------------

#main -------------------------------------------------------------------

x = 0
lista = []

#generación de ventana
window = Tk()

window.title("Decidir que mierda hacer con Mora")
window.geometry("600x500")
window.configure(background="light blue")

#descripciones
label1 = Label(window, text="Introduzca la cantidad de ítems",font="Helvetica 16", bd="3", background="light grey")
label1.place(relx = 0.5, rely= 0.35, anchor=CENTER)

#primer entry del número
texto1 = Entry(window, font = "Helvetica 17", width = 26)
texto1.bind("<Return>", cantidad_items)
texto1.place(relx = 0.5, rely=0.45, anchor=CENTER)

#firma
firma = Label(window, text="HermesBV",font = "Times 10", background= "light blue")
firma.place(relx = 1, rely= 1, anchor=SE)

#botón ejecución del input
boton1 = Button(window, text = "Ingresar", command = cantidad_items)
boton1.place(relx = 0.5, rely = 0.55, anchor= CENTER)

window.mainloop()

只需将 event 参数设为可选:

def cantidad_items(event=None):
    ...

只要该函数实际上不需要 event 对象即可正常运行,您现在可以在绑定中使用该函数,也可以将其用作 command 选项的值。

texto1.bind("<Return>", cantidad_items)
boton1 = Button(..., command = cantidad_items)