【问题标题】:Displaying different images with Tkinter [duplicate]使用 Tkinter 显示不同的图像 [重复]
【发布时间】:2021-03-06 22:33:55
【问题描述】:

我在尝试使用 Tkinter 显示图像时遇到问题。我在名为 filename1、filename2 和 filename3 的文件夹中有 3 个文件。我想通过使用两个不同的按钮来显示它们。 filename1 应该在不单击按钮的情况下显示,然后 filename2 和 filename3 应该通过单击其他按钮显示。但是,这不起作用。

最终发生的事情是,只有 filename3 正在加载,并且没有一个按钮起作用。我不知道为什么会这样。这是我尝试过的代码:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

root.geometry("1000x500")
root.resizable(width=True, height=True)

def open_img(name):
    filepath = fr"C:\Users\me\Desktop\folder/{name}.jpg"
    img = Image.open(filepath)
    img = img.resize((1000, 500), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.grid(row = 2, column=1)

open_img(filename1)    
    
btn1 = Button(root, text='open image1', command=open_img("filename2")).grid(row=3, column=1)
btn2 = Button(root, text='open image2', command=open_img("filename3")).grid(row=4, column=1)
    
root.mainloop()

这是结果,仅显示文件名 3。按钮不起作用。我在这里做错了什么?

【问题讨论】:

  • 您知道btn1btn2 将永远是None。欲了解更多信息,请阅读this

标签: python image tkinter


【解决方案1】:

当您创建按钮时,您会运行命令,因为您以括号结束它。

command=open_img("filename2")

要为函数分配参数,您可以使用 lambda 函数:

command=lambda: open_img("filename2")

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2016-12-16
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多