【问题标题】:Tkinter 2.7- image won't show up in the window with Tk.mainloop() [duplicate]Tkinter 2.7-图像不会显示在带有 Tk.mainloop() 的窗口中 [重复]
【发布时间】:2018-09-16 20:36:05
【问题描述】:
from Tkinter import Tk, PhotoImage, Label
def start_up():
    app = Tk()
    app.title("Tower")
    app.geometry('600x900')
    photo = PhotoImage("Python.png")
    label = Label(app, image = photo)
    label.pack()
    app.mainloop()
start_up()

我目前正在努力使用 tkinter 2.7。我无法显示我想要的图像,因此请查看我的代码并帮助我修复它。谢谢。

【问题讨论】:

  • 抱歉,我投票决定在那里关闭一分钟,但再看一遍,我认为您的问题与 stackoverflow.com/questions/27430648/… 的原因不同。
  • 你必须pack()标签之前你调用mainloop()
  • 我应用了更改,但仍然是白屏。

标签: python python-2.7 tkinter


【解决方案1】:
from Tkinter import 

这是一个语法错误。使用from 语法时,您需要列出要导入的名称。 (或星号来导入所有内容,但这不是一个好习惯,因为它会不必要地污染您的命名空间)

from Tkinter import Tk, PhotoImage, Label

 

label = Label(app, image = photo)
app.mainloop()
label.pack()

在调用 mainloop 之前,您应该 pack() 您的小部件。将其更改为:

label = Label(app, image = photo)
label.pack()
app.mainloop()

 

photo = PhotoImage("Python.png")

如果您想将文件名传递给 PhotoImage,您应该使用 file 关键字参数。此外,PhotoImage 不知道如何打开 png。尝试使用 gif 或 pgm 等格式。

photo = PhotoImage(file="Python.gif")

或者,安装第三方库 Pillow,并使用其 ImageTk.PhotoImage 类,它支持多种图像格式,包括 png。

from PIL import Image, ImageTk
img = Image.open("python.png")
photo = ImageTk.PhotoImage(img)
label = Label(app, image = photo)

最终结果:

from Tkinter import Tk, PhotoImage, Label
def start_up():
    app = Tk()
    app.title("Tower")
    app.geometry('600x900')
    photo = PhotoImage(file="Python.gif")
    label = Label(app, image = photo)
    label.pack()
    app.mainloop()
start_up()

【讨论】:

  • _tkinter.TclError: could't open "Python.gif": no such file or directory 我将 png 转换为 gif 并运行代码,但出现了错误消息.我尝试通过将 gif 拖到同一目录中来修复它,但它没有做任何事情。
  • @jaxk 图片必须放在current working directory。或者,使用r'C:\Users\whatever\Python.gif' 之类的绝对路径。或者将路径设为relative to the python script
猜你喜欢
  • 2017-10-02
  • 1970-01-01
  • 2018-04-18
  • 2019-01-02
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
相关资源
最近更新 更多