圆角按钮 tkinter python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42579927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:55:22  来源:igfitidea点击:

Rounded button tkinter python

pythontkintertkinter-canvas

提问by Martinn Roelofse

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

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

I found the following code:

我找到了以下代码:

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

but I get the following error:

但我收到以下错误:

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

回答by Simon

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

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

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:

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

Click here to see image

单击此处查看图像

Next insert the image in a button with PhotoImagelike this:

接下来将图像插入按钮中,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")

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

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

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

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

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

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

回答by avysk

You need to create root window first (or some other widget) and give it to your CustomButtontogether with different parameters (see definition of __init__method).

您需要首先创建根窗口(或其他一些小部件)并将其CustomButton与不同的参数一起提供给您(参见__init__方法的定义)。

Try instead of app = CustomButton()the following:

尝试而不是app = CustomButton()以下内容:

app = tk.Tk()
button = CustomButton(app, 100, 25, 'red')
button.pack()
app.mainloop()

回答by Brian

I made this rounded rectangle button if anyone was looking for more of an apple look or something. For convenience here are the arguments:

如果有人正在寻找更多苹果外观或其他东西,我制作了这个圆角矩形按钮。为方便起见,这里是参数:

RoundedButton(parent, width, height, cornerradius, padding, fillcolor, background, command)

Note: If the corner radius is greater than half of the width or height an error message will be sent in the terminal. Pill shapes can still be made through if you set the corner radius to exactly half of the height or width.

注意:如果拐角半径大于宽度或高度的一半,终端将发送错误消息。如果您将拐角半径设置为高度或宽度的一半,则仍然可以制作药丸形状。

Finally the code:

最后是代码:

from tkinter import *
import tkinter as tk

root = Tk()

class RoundedButton(tk.Canvas):
    def __init__(self, parent, width, height, cornerradius, padding, color, bg, command=None):
        tk.Canvas.__init__(self, parent, borderwidth=0, 
            relief="flat", highlightthickness=0, bg=bg)
        self.command = command

        if cornerradius > 0.5*width:
            print("Error: cornerradius is greater than width.")
            return None

        if cornerradius > 0.5*height:
            print("Error: cornerradius is greater than height.")
            return None

        rad = 2*cornerradius
        def shape():
            self.create_polygon((padding,height-cornerradius-padding,padding,cornerradius+padding,padding+cornerradius,padding,width-padding-cornerradius,padding,width-padding,cornerradius+padding,width-padding,height-cornerradius-padding,width-padding-cornerradius,height-padding,padding+cornerradius,height-padding), fill=color, outline=color)
            self.create_arc((padding,padding+rad,padding+rad,padding), start=90, extent=90, fill=color, outline=color)
            self.create_arc((width-padding-rad,padding,width-padding,padding+rad), start=0, extent=90, fill=color, outline=color)
            self.create_arc((width-padding,height-rad-padding,width-padding-rad,height-padding), start=270, extent=90, fill=color, outline=color)
            self.create_arc((padding,height-padding-rad,padding+rad,height-padding), start=180, extent=90, fill=color, outline=color)


        id = shape()
        (x0,y0,x1,y1)  = self.bbox("all")
        width = (x1-x0)
        height = (y1-y0)
        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()

def test():
    print("Hello")

canvas = Canvas(root, height=300, width=500)
canvas.pack()

button = RoundedButton(root, 200, 100, 50, 2, 'red', 'white', command=test)
button.place(relx=.1, rely=.1)

root.mainloop()

回答by frederick99

You are not passing any arguments to the constructor.

Precisely, in this line

您没有将任何参数传递给构造函数。

准确地说,在这一行

app = CustomButton()

you need to pass the arguments that were defined in the constructor definition, namely the parent, width, heightand color.

你需要通过在构造函数的定义,即中定义的参数parentwidthheightcolor