【问题标题】:Problems with multiple Tkinter buttons [duplicate]多个 Tkinter 按钮的问题 [重复]
【发布时间】:2017-10-13 10:28:47
【问题描述】:

我正在工作,但无法开始工作,我写了一个我认为可以显示问题的示例:

from tkinter import *

listing = [1, 2, 3, 4]

def PressedButton(listing):
    print(listing)

global root
root = Tk()
ListButton = []
for i in range(0, len(listing)):
    ListButton.append(Button(root, text= listing[i], command = lambda: 
PressedButton(listing[i])))
    ListButton[i].grid(row = i)

当我运行它时,无论我选择什么按钮,我总是打印数字 4,但所有按钮上都有各自正确的数字。

非常感谢你们提供的任何帮助。

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    好吧,你的代码中有很多与不良编程实践相关的事情,当然你必须阅读更多关于lambda 表达式的内容,所以目前我所能做的就是为你提供一个解决方案来编写你的代码工作。

    改变这个:

    ... command = lambda: PressedButton(listing[i]) ...
    

    ... command = lambda i=i: PressedButton(listing[i]) ...
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2019-03-22
      • 1970-01-01
      相关资源
      最近更新 更多