圆角按钮 tkinter python [英] Rounded button tkinter python

查看:73
本文介绍了圆角按钮 tkinter python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get rounded buttons for my script using tkinter.

我发现以下代码:

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 中制作圆形按钮的一个非常简单的方法是使用图像.

A very easy way to make a rounded button in tkinter is to use an image.

首先创建您希望按钮看起来像的图像,将其另存为 .png 并删除外部背景,使其四舍五入,如下所示:

First create an image of what you want you button to look like save it as a .png and remove the outside background so it is rounded like the one below:

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

Next insert the image in a button with PhotoImage like this:

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",按钮边框将被移除.

Ensure to use border="0" and the button border will be removed.

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

I added the self.roundedborder["bg"] = "white" so that the the background the background of the button is the same as the Tkinter window.

最重要的是,您可以使用任何您喜欢的形状,而不仅仅是普通的按钮形状.

The great part is that you can use any shape you like not just the normal button shapes.

这篇关于圆角按钮 tkinter python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆