该程序有一个条目和一个按钮,用于提交其中的信息。 首先,需要一个 int 值来知道你要输入信息多少次,然后收集所有输入后,它会随机显示其中一个。 我绑定了<"Return">键,因此您不必手动单击按钮,而是要考虑到两个不同的功能正在运行的事实,我在重新绑定键以使用第二个函数时遇到问题。我该如何解决?
window.title("Decidir que mierda ver con Mora")
window.geometry("600x500")
window.configure(background="light blue")
x = None
item = ""
list = []
#cantidad de items (el event activa el Enter)
def cantidad_items(event):
x= int(texto1.get())
texto1.delete(0, END)
texto1.bind("<Return>",añadir)
boton1.configure(text = "Ingresar", command= lambda:añadir(x))
#nombre de los items
def añadir(x):
item = texto1.get()
list.append(item)
texto1.delete(0, END)
if len(list)== x:
texto1.destroy()
boton1.destroy()
rando = random.choice(list)
resultado = Label(window, text=rando, font= "Helvetica 30")
resultado.place(relx=0.5, rely=0.5, anchor= CENTER)
#primer entry del número
texto1 = Entry(window, font = "Helvetica 20", width = 22)
texto1.bind("<Return>", cantidad_items)
texto1.place(relx = 0.5, rely=0.45, anchor=CENTER)
#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()
如果您在两个函数中使用print()
,那么您会看到它重新绑定<Return>
。
你真正的问题是不同的。
在cantidad_items()
中,您必须使用global x
来通知函数以将x = ...
分配给外部/全局变量。如果没有global
它会创建局部变量x
Bind 使用参数event
执行añadir(x)
,并创建局部变量x
并将event
分配给x
。同时,在command=
您使用全局x
运行它,并将全局x
分配给本地x
。您可以创建añadir(event=None)
以在与event
绑定和command=añadir
中运行它,没有任何值 - 然后当您尝试从x
获取值时,它将从全局x
from tkinter import *
import random
#cantidad de items (el event activa el Enter)
def cantidad_items(event):
global x
print('cantidad_items')
x = int(texto1.get())
texto1.delete(0, END)
texto1.bind("<Return>", añadir)
boton1.configure(text="Ingresar", command=añadir)
#nombre de los items
def añadir(event=None): # bind() runs with argument, command= runs without argument
print('añadirb')
item = texto1.get()
data.append(item)
texto1.delete(0, END)
if len(data) == x:
texto1.destroy()
boton1.destroy()
rando = random.choice(data)
resultado = Label(window, text=rando, font="Helvetica 30")
resultado.place(relx=0.5, rely=0.5, anchor=CENTER)
# --- main ---
x = 0
data = [] # don't use name `list`
window = Tk()
window.title("Decidir que mierda ver con Mora")
window.geometry("600x500")
window.configure(background="light blue")
#primer entry del número
texto1 = Entry(window, font="Helvetica 20", width=22)
texto1.bind("<Return>", cantidad_items)
texto1.place(relx=0.5, rely=0.45, anchor=CENTER)
#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()