【问题标题】:My tkinter image show up as a black screen我的 tkinter 图像显示为黑屏
【发布时间】:2020-05-24 09:49:10
【问题描述】:

我正在尝试为我的学校作业编写游戏代码。在这个游戏中,我想要一个静音按钮,所以我在标签框顶部制作了一个按钮并将其放置在标签中。我不知道它有什么问题,但图像不显示。我试图通过将其分配给临时变量来创建本地副本,但它仍然没有出现。这是我的代码:

from tkinter import ttk
from PIL import Image, ImageTk

root = Tk()

topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)

btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )

mute_image = Image.open("pygame/mute.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)

mute_button = Button( btnframe, width = 50, height = 50, command = Mute, image = mute_icon)
mute_button.image = mute_icon
mute_button.pack()

root.mainloop()

请放轻松,这是我第一次编写游戏代码:)) 提前致谢:))

【问题讨论】:

  • 尝试在 mute_image 之前添加它,它可能会工作 global mute_imageglobal mute_icon 我实际上尝试运行此代码,它对我来说没有任何问题
  • @CoolCloud 没有任何问题:在globalscope 上使用global ... 是没用的。
  • 无法重现您的行为,对我有用,请参阅 repl.it。验证您的图片!
  • 是的,它也对我有用,我认为真正的问题是

标签: python image tkinter


【解决方案1】:

您是否收到任何错误消息。我稍微修改了您的代码,它抱怨未定义按钮回调函数。在我补充说这一切似乎都有效之后。

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)

btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )

def Mute():
    pass

mute_image = Image.open("images/beer.png")  
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)

mute_button = Button(btnframe, width=50, height=50,
                     command=Mute, image=mute_icon)
mute_button.image = mute_icon
mute_button.pack()

root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多