我有以下代码生成5x5尺寸的随机按钮网格:
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()
我已经实现了命令功能,并通过lambda传递了一个参数,如下所示:
redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda: numberClick(num))
现在,当我单击一个按钮时,函数调用应打印与之关联的文本值。相反,它只打印相同的值,即num变量中的最后一个赋值:当我单击按钮20时输出
任何解决方法?TIA。
只需将您的按钮更改为:
redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda num=num: numberClick(num))
这应该可以解决问题,它将num
在lambda中存储值,而不仅仅是循环并使用的最后一个值num
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句