如何将.PNG文件正确附加到TKINTER按钮中?

2024-04-20 06:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个战舰游戏,下面有一个函数,用来创建一个以爆炸图像为背景的新按钮。我正在使用Mac&;python 3.7

global redraw_gameboard
global Player
global AI_player    

script_dir = os.path.dirname(__file__)
rel_path = "explode.png"

image = ImageTk.PhotoImage(file=os.path.join(script_dir, rel_path))

new_button = Button(redraw_gameboard, 
                    height = 2, 
                    width = 4, 
                    command= already_shot,
                    image=image)

new_button.grid(row = row, column = column)

这就是即将出现的情况:

image


1条回答
网友
1楼 · 发布于 2024-04-20 06:41:32

我不知道你期望什么,因为我不知道“explode.png”图像是什么样子。此外,在询问有关stackoverflow的问题时,请始终尝试发布minimal reproducible example

然而,据我所知,问题可能是因为图像比按钮大,而且被裁剪了。然后,按钮中仅显示图像的左上部分

建议的解决办法: (如果尚未安装枕头包,则需要安装它)

import os
from PIL import Image, ImageTk
import tkinter

# Sizes in pixels
BUTTON_HEIGHT = 40
BUTTON_WIDTH = 40

root = tkinter.Tk()

script_dir = os.path.dirname(__file__)
rel_path = "explode.png"

image = Image.open(os.path.join(script_dir, rel_path))
image = image.resize((BUTTON_WIDTH,BUTTON_HEIGHT))
imtk = ImageTk.PhotoImage(image)

# Using a void image for other buttons so that the size is given in pixels too
void_imtk = tkinter.PhotoImage(width=BUTTON_WIDTH, height=BUTTON_HEIGHT)


def create_button(row, column, im):
    new_button = tkinter.Button(root,
                                height = BUTTON_HEIGHT,
                                width = BUTTON_WIDTH,
                                image=im)
    new_button.grid(row = row, column = column)


create_button(0,0, imtk)
create_button(0,1, void_imtk)
create_button(1,0, void_imtk)
create_button(1,1, imtk)


root.mainloop()

当然,您需要对您的程序进行一些更改,例如使用您的小部件架构

相关问题 更多 >