【问题标题】:How do I store multiple values generated in a for loop to pass to a funtion within a tkinter button loop?如何存储在 for 循环中生成的多个值以传递给 tkinter 按钮循环中的函数?
【发布时间】:2021-01-19 19:36:09
【问题描述】:

我有一个 tkinter 窗口,它构建了必要数量的按钮,相应地命名它们,然后显示相应的图像。我希望按钮在按下时打印与图像对应的正确文件名。我试过lambda,但这只会通过最后一个参数。我该怎么做?

images 是我正在使用的目录中的文件名列表。

def print_filename(i):
    print(i)


window = Tk()
window.title('Test Window')

for i in images:
    my_image = PhotoImage(master = window, file = i)
    label = Label(window, image = my_image)
    label.image=my_image
    label.grid(row = 1, column = c)
    b = Button(window, text=f'button {(c+1)}', command=lambda: print_filename(i))
    b.grid(row=0, column=c)
    c += 1

window.mainloop()

这是它运行时的样子:

该按钮应在按下时打印出图像的文件名。 例如:pdf_1.png

【问题讨论】:

  • 试试command=lambda i=i: print_filename(i)让我知道
  • 做到了!谢谢!

标签: python image function button tkinter


【解决方案1】:

来自 Tkinter 的文档:

Tkinter 的 Button 小部件不会将任何信息传递给回调。

对于这样的简单情况,您可以使用 lambda 表达式作为 Tkinter 和回调函数之间的链接:

def callback(number):
   print(number) 

Button(text="one",   command=lambda: callback(1)).pack()
Button(text="two",   command=lambda: callback(2)).pack()
Button(text="three", command=lambda: callback(3)).pack()

使用上面提到的方式将图片的索引传递给print_filename

【讨论】:

  • OP 似乎在使用 python 3.x
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 2018-10-15
  • 2021-03-13
  • 2018-05-30
  • 2015-04-03
相关资源
最近更新 更多