我试图在tkinter中创建一个非常简单的图像查看器,有两个简单的按钮视图和关闭。我有关闭按钮按预期运行,但我无法让我的视图按钮在我的文件目录中打开指定的图像。我已经尝试导入ImageTK
来编写一个按钮命令来打开它,但到目前为止还没有成功。
import tkinter as tk
from PIL import ImageTk,Image
class image_viewer:
def __init__(self, win):
self.root = win
self.root.title('ImageViewer')
self.root.geometry('400x350')
self.btnView = tk.Button(text='View', command= ImageTk.PhotoImage(Image.open(r"C:UsersSteveSmitheclipse-workspaceSteveSmith-ex1srcrawpythonIsFun.jpg")))
self.btnView.pack(side=tk.LEFT)
self.btnView.place(x=20, y=265)
self.btnClose = tk.Button(text='close', command=self.root.destroy)
self.btnClose.pack(side=tk.LEFT)
self.btnClose.place(x=65, y=265)
def main():
root = tk.Tk()
image_viewer(root)
root.mainloop()
if __name__ == '__main__':
main()
你的代码中有许多错误,以前我在选择其中一个错误后关闭了它,并将其标记为另一个问题的副本,该问题在涵盖该问题之前已经问过并回答过。
然而,根据你所做的评论和仔细考虑后,我决定重新打开它,并尝试解决我看到的所有或至少大部分问题-否则它可能会花费你相当长的时间来解决所有问题。
结果如下:
from PIL import ImageTk, Image
import tkinter as tk
class ImageViewer:
def __init__(self, root, image_filename):
self.root = root
self.image_filename = image_filename
self.root.title('ImageViewer')
self.root.geometry('400x350')
self.canvas = tk.Canvas(self.root, width=300, height=300)
self.canvas.place(x=10, y=10)
self.btnView = tk.Button(text='View', command=self.view_image)
self.btnView.place(x=20, y=265)
self.btnClose = tk.Button(text='close', command=self.root.destroy)
self.btnClose.place(x=65, y=265)
def view_image(self):
self.img = ImageTk.PhotoImage(Image.open(self.image_filename)) # Keep ref to image.
self.canvas.create_image(20, 20, anchor=tk.NW, image=self.img)
def main(image_filename):
root = tk.Tk()
ImageViewer(root, image_filename)
root.mainloop()
if __name__ == '__main__':
main(r"C:UsersSteveSmitheclipse-workspaceSteveSmith-ex1srcrawpythonIsFun.jpg")