gpt4 book ai didi

python - 如何制作圆形按钮 tkinter?

转载 作者:太空狗 更新时间:2023-10-29 22:12:32 25 4
gpt4 key购买 nike

我正在尝试使用 tkinter 为我的脚本获取圆形按钮。

我在对 How to make a Button using the tkinter Canvas widget? 的回答中找到了以下代码:

from tkinter import *
import tkinter as tk

class CustomButton(tk.Canvas):
def __init__(self, parent, width, height, color, command=None):
tk.Canvas.__init__(self, parent, borderwidth=1,
relief="raised", highlightthickness=0)
self.command = command

padding = 4
id = self.create_oval((padding,padding,
width+padding, height+padding), outline=color, fill=color)
(x0,y0,x1,y1) = self.bbox("all")
width = (x1-x0) + padding
height = (y1-y0) + padding
self.configure(width=width, height=height)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)

def _on_press(self, event):
self.configure(relief="sunken")

def _on_release(self, event):
self.configure(relief="raised")
if self.command is not None:
self.command()
app = CustomButton()
app.mainloop()

但我收到以下错误:

TypeError: __init__() missing 4 required positional arguments: 'parent', 'width', 'height', and 'color'

最佳答案

在 tkinter 中制作圆形按钮的一种非常简单的方法是使用图像。

首先创建一个你希望按钮看起来像的图像,将其保存为 .png 并删除外部背景,使其像下面的一样圆润:

Click here to see image

接下来将图像插入带有 PhotoImage 的按钮中,如下所示:

self.loadimage = tk.PhotoImage(file="rounded_button.png")
self.roundedbutton = tk.Button(self, image=self.loadimage)
self.roundedbutton["bg"] = "white"
self.roundedbutton["border"] = "0"
self.roundedbutton.pack(side="top")

确保使用 border="0" 按钮边框将被移除。

我添加了 self.roundedborder["bg"] = "white" 以便按钮的背景与 Tkinter 窗口的背景相同。

最棒的是你可以使用任何你喜欢的形状,而不仅仅是普通的按钮形状。

关于python - 如何制作圆形按钮 tkinter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com