这是在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 或类似的东西,关键是不要导入所有东西,除非你真的知道你在做什么;名称冲突是问题所在。