我有以下代码生成5x5尺寸的随机按钮网格:
import org.openqa.selenium.By;
我已经实现了命令功能,并通过lambda传递了一个参数,如下所示:
import tkinter as tk
from tkinter import *
from tkinter import messagebox
import random
def numberClick(num):
messagebox.showinfo('Message', 'You clicked the '+str(num)+' button!')
root = Tk()
#root.geometry("200x200")
w = Label(root, text='Welcome to Bingo!')
linear_array = [i for i in range(1,26)]
random_array = []
for i in range(1,26):
temp = random.choice(linear_array)
linear_array.remove(temp)
random_array.append(temp)
for i in range(25):
num = random.choice(random_array)
#tk.Label(root,text=num).grid(row=i//5, column=i%5)
redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda: numberClick(num))
redbutton.grid(row=i//5, column=i%5)
root.mainloop()
现在,当我单击按钮时,函数调用应打印分配给它的文本值。相反,它只打印相同的值,即num变量中的最后一个赋值: Output when i clicked on button 20
任何解决方法?? TIA。
答案 0 :(得分:1)
只需将按钮更改为:
redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda num=num: numberClick(num))
这应该可以解决问题,它将num
的值存储在lambda中,而不仅仅是循环并使用num
的最后一个值。
答案 1 :(得分:1)
我正要指出一件事,即酷云,但我还要补充一点,您将随机化两次,以便获得重复的数字。
第一个for循环将random_array中的数字1-25随机化,但是随后在第二个循环中,您从该列表中随机选择一个元素,而在初始化num时不删除它。我将第二个循环写为:
zookeeper