Python 无法使用tkinter显示图像
我有以下代码:Python 无法使用tkinter显示图像,python,image,python-3.x,image-processing,tkinter,Python,Image,Python 3.x,Image Processing,Tkinter,我有以下代码: from tkinter import * import os from PIL import ImageTk, Image #Python3 version of PIL is Pillow class Scope: def __init__(self, master): self.master = master f = Frame(root) self.greet_button = Button(f
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back", command=self.back)
self.greet_button.pack(side= LEFT)
self.greet_button = Button(f, text="Detect", command=self.detect)
self.greet_button.pack(side= LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
photo = PhotoImage(file='demo.gif')
cv = Label(master, image=photo)
cv.pack(side= BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
我的第一个问题是,当我运行它时,所有的按钮和窗口都会显示出来,但没有图像。有一个正方形的占位符,指示图像应该在该框中,但实际上没有显示图像。只要键入以下内容,我就可以显示图像:
root = Tk()
photo = PhotoImage(file='demo.gif')
label = Label(root, image=photo)
label.pack()
root.mainloop()
所以,我知道这是可能的。但是我不知道我的GUI代码有什么问题。我已经试着调试了很多次,但似乎没有任何效果
第二个问题是,我完全无法在GUI中显示
jpg
文件。我试过使用每一个教程,但没有什么能完全做到这一点。理想情况下,我只希望能够显示jpg
图像,如果这不可能,我将满足于显示gif
您对photo
的引用在调用类后被Python销毁/carbage收集,因此,标签无法显示任何内容
为了避免这种情况,您必须保持对它的稳定引用,即将其命名为self.photo
:
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back") #, command=self.back)
self.greet_button.pack(side=LEFT)
self.greet_button = Button(f, text="Detect") #, command=self.detect)
self.greet_button.pack(side=LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
self.photo = PhotoImage(file='demo.gif')
cv = Label(master, image=self.photo)
cv.pack(side=BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
PS:您的代码段没有正常运行,因为缺少两个函数。Oops,似乎我找的不是正确的@BryanOakley。在这种情况下我该怎么办?删除它?它确实有一个很好的答案。我还问了这个问题的第二部分。我是否应该将问题的格式改为只包含那个?对不起,我不知道重复的内容。不过,关于stackoverflow的第二部分还有一个答案,请参阅。结论是:永远谷歌第一。学习如何高效地使用谷歌。