【发布时间】:2021-01-20 23:23:05
【问题描述】:
我有以下代码生成 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 变量中的最后一个赋值: Output when i clicked on button 20
任何解决方法? TIA。
【问题讨论】:
-
保留 25 个文本值的列表并对其进行索引以获取所选按钮的文本。
-
我该如何准确索引它?我很困惑。我也是这么想的,但是我随机生成订单,正如您在代码中看到的那样。
-
我已经添加了答案,请告诉我
-
感谢云,你的答案也是世界!!非常感谢