【发布时间】: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。按钮不起作用。我在这里做错了什么?
【问题讨论】:
-
您知道
btn1和btn2将永远是None。欲了解更多信息,请阅读this