简体   繁体   English

我的 tkinter 图像显示为黑屏

[英]My tkinter image show up as a black screen

I am trying to code a game for my school assignment.我正在尝试为我的学校作业编写游戏。 In this game, I wanted to have a mute button so I have made a button on top of a label frame and place it in a label.在这个游戏中,我想要一个静音按钮,所以我在 label 框架顶部制作了一个按钮,并将其放置在 label 中。 I don't know what is wrong with it but the image does not show up.我不知道它有什么问题,但图像不显示。 I have tried to create a local copy by assigning it to a temp variable and yet it still doesn't show up.我试图通过将其分配给临时变量来创建本地副本,但它仍然没有出现。 Here's my code:这是我的代码:

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()

Please go easy on me, this is my first time coding a game ever:)) Thanks in advance:))请 go 放轻松,这是我第一次编写游戏代码:)) 提前致谢:))

Are you getting any error messages.您是否收到任何错误消息。 I slightly modified your code and it complained abuot the button callback function was not defined.我稍微修改了您的代码,它抱怨按钮回调 function 未定义。 After I added that it all seems to work.在我补充说这一切似乎都有效之后。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM