[英]How do I put an image in python tkinter?
我正在尝试将 JPEG 图像插入 Python Tkinter window,但它不起作用。 我试过这个:
imageFile = "logo.jpg"
window.im1 = Image.open(imageFile)
当我运行它说:
line 21, in <module>
window.im1 = Image.open(imageFile)
AttributeError: type object 'Image' has no attribute 'open'
我试过了:
imageFile = "logo.jpg"
window.im1 = PhotoImage.open(imageFile)
但它说:
line 20, in <module>
window.im1 = PhotoImage.open(imageFile)
AttributeError: type object 'PhotoImage' has no attribute 'open'
我也试过:
imageFile = "logo.jpg"
window.im1 = Image(imageFile)
但它说:
line 4006, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: image type "logo.jpg" doesn't exist
最后,我尝试了:
imageFile = "logo.jpg"
window.im1 = PhotoImage(imageFile)
它运行正常,但没有任何显示。
有没有其他方法可以放置图像?
我发现了!
希望对你有帮助
from PIL import Image, ImageTk
from tkinter import Tk, Frame, Label
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Label")
self.img = Image.open("C:\\tatras.jpg")
tatras = ImageTk.PhotoImage(self.img)
label = Label(self, image=tatras)
label.image = tatras
label.pack()
self.pack()
def setGeometry(self):
w, h = self.img.size
self.parent.geometry(("%dx%d+300+300") % (w, h))
root = Tk()
ex = Example(root)
ex.setGeometry()
root.mainloop()
Output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.