【问题标题】:I don't even know how to describe this problem我什至不知道如何描述这个问题
【发布时间】:2020-08-17 21:19:58
【问题描述】:

我正在尝试将图片插入 tkinter 按钮
这是我的代码:

from tkinter import *
import tkinter as tk
from PIL import Image,ImageTk,ImageOps

class main_class(tk.Tk):
    def __init__(self):
        self.window = tk.Tk()
        self.window.geometry("1920x1080")
        self.window.configure(background='grey')

        #opening play pic and resizing it to fit into button
        self.play_pic = Image.open("play_pic.jpg")
        self.play_pic_size = (11,49)
        self.play_pic = ImageOps.fit(self.play_pic,self.play_pic_size,Image.ANTIALIAS)
        self.play_pic = ImageTk.PhotoImage(self.play_pic)


        #play button
        self.play_button = Button(self.window,image=self.play_pic,command = self.play,height =11 ,width = 49).place(x=800,y = 180)


        self.window.mainloop()

    def play(self):
        print('Everything is working fine so far')


#creating an object
object = main_class()
object.play()

结果应该是这样的:

这就是正在发生的事情:

这是“play_pic.jpg”,以备不时之需:

非常感谢任何帮助!

【问题讨论】:

标签: python image user-interface tkinter python-imaging-library


【解决方案1】:

您的代码中有两个错误。首先,您尝试使用以下语句将图像转换为仅 11 像素宽 x 49 像素高:

    self.play_pic_size = (11,49)
    self.play_pic = ImageOps.fit(self.play_pic,self.play_pic_size,Image.ANTIALIAS)

其次,无论图像大小如何,您都强制按钮宽度为 11 像素,高度为 49 像素:

    self.play_button = Button(...,height =11 ,width = 49  ).place(x=800,y = 180)

如果您要麻烦地将图像大小调整为您想要的大小,则无需要求按钮具有特定大小。它会自动缩小或扩大以适合图像。

第一步是将self.play_pic_size 定义为合理的大小。接下来,从按钮定义中删除 height =11 ,width = 49

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 2022-11-11
    • 2011-07-12
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2021-04-15
    • 2020-04-17
    • 1970-01-01
    相关资源
    最近更新 更多