-1

I am trying to insert a pic into a tkinter button
This is my code:

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

This is what the result should look like :

enter image description here

And this is what is happening : enter image description here

This is the "play_pic.jpg" in case you need it:

enter image description here

Any help is much appreciated!!

1 Answers1

0

You have two mistakes in your code. First, you're trying to convert the image to be only 11 pixels wide by 49 pixels tall with these statements:

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

Second, regardless of the image size, you're forcing the button to be a width of 11 pixels and height of 49 pixels:

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

If you're going to the trouble of resizing the image to be what you want, there is no need to request the button be a specific size. It will automatically shrink or expand to fit the image.

The first step is to define self.play_pic_size to be a reasonable size. Next, remove height =11 ,width = 49 from the button definition.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685