圆角按钮 tkinter python

编程入门 行业动态 更新时间:2024-10-24 07:28:12
本文介绍了圆角按钮 tkinter python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 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)
        selfmand = 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 selfmand is not None:
            selfmand()
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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:38:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   圆角   python   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!