【问题标题】:The background doesn't round the button tkinter背景不圆按钮 tkinter
【发布时间】:2021-11-27 04:01:49
【问题描述】:

我正在使用 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:

有人可以帮我吗?谢谢

【问题讨论】:

  • Label 没有圆角(据我所知)。所以即使图像是四舍五入的,它也不会反映在tk.Label
  • 你知道哪个模块可以做到这一点
  • 哪个模块可以圆按钮?
  • 使用不同的框架,例如 PyQt 或 PyGtk。
  • @Art不一定,你可以在Canvas中创建圆角按钮,如果你使用圆角的图像并为按钮设置relief='flat',它们会不会有点圆?

标签: python tkinter


【解决方案1】:

这是在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()

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

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

【讨论】:

  • 按钮好像还没有圆角。
  • @HuyVuQuang 按钮的形状/图像必须是圆形的
  • 是的。它们总是圆形的
  • @huyvuquang 那么问题是什么?顺便说一句,如果您希望它们是圆形的,则不能使用 Button 创建按钮
  • 所以你想让我为我的按钮设置图片?
猜你喜欢
  • 2013-07-19
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多