背景不环绕按钮tkinter

2024-05-18 10:52:52 发布

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

我正在使用tkinter创建GUI。我使用PIL导入图像作为背景。这是我的密码:

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

在我的应用程序中,按钮是圆形的。但是当我使用图像时,背景与圆形按钮不匹配,这里是image:

有人能帮我吗?谢谢


Tags: 图像image密码imgpiltitletkintergui
1条回答
网友
1楼 · 发布于 2024-05-18 10:52:52

以下是如何在tkinter中创建圆形“按钮”(决定可见形状的是图像的外观):

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

大部分解释都在代码注释中,但请注意,绑定序列适用于整个图像,但图像始终是方形的,因此您可以单击可见部分之外的按钮,但只有在图像移动时,才可以创建没有此类问题但需要一些数学运算的按钮

重要的(建议):
我强烈建议不要使用通配符(*)当导入一些东西时,你应该要么导入你需要的东西,例如from module import Class1, func_1, var_2等等,要么导入整个模块:import module然后你也可以使用别名:import module as md或者类似的东西,关键是除非你真正知道你在做什么,否则不要导入所有东西;名字冲突是个问题

相关问题 更多 >