The background doesn't round the button tkinter

Viewed 246

I am using tkinter to create a GUI. I use PIL to import an image as the background. Here is my code:

root = tk.Tk()
root.title("DFUInfo-v1")
img = ImageTk.PhotoImage(Image.open("background.jpg"))  
l=Label(image=img)
l.pack()
root.configure(bg='white')   

root.geometry("490x280")

In my app, buttons are rounded. But when I use the image, the background does not match the round buttons, here is the image:

Can somebody help me pls? Thanks

1 Answers

Here is how you can create rounded "buttons" in tkinter (what determines the visible shape is how the image looks):

from tkinter import Tk, Canvas
from PIL import Image, ImageTk


# use your images here
# open your images (my preference is to use `.open` before initialising `Tk`)
img = Image.open('rounded.png')
# resize to match window geometry
bg = Image.open('space.jpg').resize((500, 400))


# the function to call when button clicked
def func(event=None):
    print('clicked')


root = Tk()
root.geometry('500x400')
# here are the converted images
photo = ImageTk.PhotoImage(img)
bg = ImageTk.PhotoImage(bg)

# from now on this will be the "root" window
canvas = Canvas(root, highlightthickness=0)
canvas.pack(fill='both', expand=True)
# add background
canvas.create_image(0, 0, image=bg, anchor='nw')

# create button and you have to use coordinates (probably can make
# custom grid system or sth)
btn = canvas.create_image(250, 200, image=photo, anchor='c')
# bind the "button" to clicking with left mouse button, similarly
# as `command` argument to `Button`
canvas.tag_bind(btn, '<Button-1>', func)

root.mainloop()

Most of the explanation is in the code comments, but note that the bound sequence works for the whole image but images are always square so you can click the button being outside of the visible part but only as far as the image goes, it is most certainly possible to create a button that doesn't have such issues but that requires some math

Important (suggestion):
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.

Related