【问题标题】:Tkinter : How to pass a button's text as an argument to a function when button is clickedTkinter:单击按钮时如何将按钮的文本作为参数传递给函数
【发布时间】: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 个文本值的列表并对其进行索引以获取所选按钮的文本。
  • 我该如何准确索引它?我很困惑。我也是这么想的,但是我随机生成订单,正如您在代码中看到的那样。
  • 我已经添加了答案,请告诉我
  • 感谢云,你的答案也是世界!!非常感谢

标签: python tkinter


【解决方案1】:

只需将您的按钮更改为:

redbutton = Button(root, text = num, fg ='red',height = 3, width = 5,command=lambda num=num: numberClick(num))

这应该可以解决问题,这会将 num 的值存储在 lambda 中,而不仅仅是循环并使用 num 的最后一个值。

【讨论】:

    【解决方案2】:

    我正要指出同样的东西酷云,但我还想补充一点,你正在随机化两次,这样你可能会得到重复的数字。

    第一个 for 循环将 random_array 中的数字 1-25 随机化,但是在第二个循环中,您从该列表中随机选择一个元素,而在初始化 num 时不会将其删除。我将第二个循环写为:

    for i in range(25):
        num = random_array[i]
        redbutton = Button(root, text = num, fg ='red',height = 3, width = 5, command=lambda n=num: numberClick(n))
        redbutton.grid(row=i//5, column=i%5)
    

    【讨论】:

    • 我实际上是在第一个循环中从 linear_array 中删除元素,这样我就不会得到重复的数字。
    • @PriyanshGupta 您在第二个循环中使用了random.choice(),它将从random_array 获得相同的数字。您可以在图片链接中看到重复项。
    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多