【问题标题】:How do i properly attach a .PNG file into a TKINTER button?如何正确地将 .PNG 文件附加到 TKINTER 按钮中?
【发布时间】:2020-04-22 09:41:51
【问题描述】:

我正在做一个战舰游戏和下面的一个函数,它执行以创建一个以爆炸图像作为背景的新按钮。我正在使用 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的引用。尝试添加new_button.image = image
  • @acw1668 谢谢哥们,它终于对我有用了!!

标签: python tkinter tk tkinter-canvas


【解决方案1】:

我不确定您的期望,因为我不知道“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()

当然,您会希望对您的程序进行一些更改,例如使用您的小部件架构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多