首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在tkinter上使用填充圆角按钮

如何在tkinter上使用填充圆角按钮
EN

Stack Overflow用户
提问于 2021-09-07 14:54:01
回答 2查看 645关注 0票数 0

我想要一个像图片上那样的圆形按钮。

用python tkinter改变按钮的背景颜色(如果你教我,我不知道如何使用类,我也可以使用它)。我试过了

代码语言:javascript
运行
复制
button = CustomButton(window, 100, 25, 'red') 

我得到了一个错误的NameError: name 'CustomButton' is not defined

这是我的代码

代码语言:javascript
运行
复制
import tkinter as tk
from tkinter import *
from tkinter import font

#declarando a variavel da janela
window = tk.Tk()

#mudando o titulo da janela
window.title('sorteio')
#colocando o favicon na aba
window.iconbitmap("./img/pinguim.ico")

#pegando a resolução do monitor e colocando em uma variavel
widthValue = window.winfo_screenwidth()
heightValue = window.winfo_screenheight()
window.geometry("%dx%d+0+0" % (widthValue,heightValue))
                           #↑  
              #passando o valor de "%dx%d" 

#deixando maximizada ao iniciar
window.state('zoomed')            

#Define image
bg = PhotoImage(file="./img/background.png")
#criando um canvas
canvas1 = Canvas(window, width=widthValue, height=heightValue, bd=0 , highlightthickness=0)#highlightthickness= 0 tira a borda branca
canvas1.pack(fill="both", expand=True)
#colocando a imagem no canvas
canvas1.create_image(0,0, image=bg , anchor="nw")
#criando texto
canvas1.create_text(900,100, text="Sorteio", font=("Roboto", 25), fill="white", anchor="center")

canvas1.create_text(680,300, text=" Sortear entre:", font=("Roboto", 12), fill="white" )
inputMin = Entry(canvas1)
canvas1.create_window(800, 300, window=inputMin, height=25, width=120)
inputMin.insert(0, "minimo")
inputMin.config(fg="#808080", font="Roboto")

canvas1.create_text(885,300, text="e:", font=("Roboto",12), fill="white")
inputMax = Entry(canvas1)
inputMax.insert(0, "maximo")
inputMax.config(fg="#808080", font="Roboto")
canvas1.create_window(955, 300, window=inputMax, height=25, width=120)


#função
def sortear():
    print("oi")

#primeiro cria o texto depois escolhe a posição dele
#textoSorteio = Label(window, text="Sorteio",font=("Roboto", 25), fg="white")#passando a janela pro texto

#textoSorteio.pack(pady=50)
button = CustomButton(window, 100, 25, 'red')
btnSorte = canvas1.create_oval()
btnSortear = Button(window, text="Sortear", width=15, height=1, pady=5,command=sortear)
btnSortear.place(x=1100, y=500)

window.mainloop()
EN

回答 2

Stack Overflow用户

发布于 2021-09-07 15:14:05

问题是,您正在使用其他人创建的类,并且没有将其包含在您的代码中。CustomButton-class需要包含在文件的顶部。

我真的强烈建议你好好读一读课程。面向对象编程是python的基础,以及如何编写更复杂的代码。

票数 0
EN

Stack Overflow用户

发布于 2021-09-08 09:05:27

您需要将该类包含在文件中或单独的文件中,然后将其导入。

下面是一个例子(圆角按钮取自here):

代码语言:javascript
运行
复制
import tkinter as tk


class RoundedButton(tk.Canvas):

    def __init__(self, master=None, text:str="", radius=25, btnforeground="#000000", btnbackground="#ffffff", clicked=None, *args, **kwargs):
        super(RoundedButton, self).__init__(master, *args, **kwargs)
        self.config(bg=self.master["bg"])
        self.btnbackground = btnbackground
        self.clicked = clicked

        self.radius = radius        
        self.text = self.create_text(0, 0, text=text, tags="button", fill=btnforeground, font=("Times", 14), justify="center")
        self.rect = self.round_rectangle(0, 0, 0, 0, tags="button", radius=radius, fill=btnbackground)

        self.tag_bind("button", "<ButtonPress>", self.border)
        self.tag_bind("button", "<ButtonRelease>", self.border)
        self.bind("<Configure>", self.resize)

        text_rect = self.bbox(self.text)
        if int(self["width"]) < text_rect[2]-text_rect[0]:
            self["width"] = (text_rect[2]-text_rect[0]) + 10

        if int(self["height"]) < text_rect[3]-text_rect[1]:
            self["height"] = (text_rect[3]-text_rect[1]) + 10

    def round_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
   
        points = [x1+radius, y1,
                x1+radius, y1,
                x2-radius, y1,
                x2-radius, y1,
                x2, y1,
                x2, y1+radius,
                x2, y1+radius,
                x2, y2-radius,
                x2, y2-radius,
                x2, y2,
                x2-radius, y2,
                x2-radius, y2,
                x1+radius, y2,
                x1+radius, y2,
                x1, y2,
                x1, y2-radius,
                x1, y2-radius,
                x1, y1+radius,
                x1, y1+radius,
                x1, y1]

        return self.create_polygon(points, **kwargs, smooth=True)

    def resize(self, event):
        text_bbox = self.bbox(self.text)

        if self.radius > event.width or self.radius > event.height:
            radius = min((event.width, event.height))

        else:
            radius = self.radius

        bg = self.itemcget(self.rect, "fill")

        width, height = event.width, event.height

        if event.width < text_bbox[2]-text_bbox[0]:
            width = text_bbox[2]-text_bbox[0] + 30

        if event.height < text_bbox[3]-text_bbox[1]:  
            height = text_bbox[3]-text_bbox[1] + 30


        self.delete(self.rect)
        self.rect = self.round_rectangle(5, 5, width-5, height-5, 
                                            radius=radius, fill=bg, tags="button")

        bbox = self.bbox(self.rect)

        x = ((bbox[2]-bbox[0])/2) - ((text_bbox[2]-text_bbox[0])/2)
        y = ((bbox[3]-bbox[1])/2) - ((text_bbox[3]-text_bbox[1])/2)

        self.moveto(self.text, x, y)
        self.tag_raise(self.text)

    def border(self, event):
        if event.type == "4":
            self.itemconfig(self.rect, fill="#d2d6d3")
            if self.clicked is not None:
                self.clicked()

        else:
            self.itemconfig(self.rect, fill=self.btnbackground)

def func():
    print("Button pressed")

root = tk.Tk()

root.columnconfigure(0, weight=1)
root.rowconfigure((0, 1, 2), weight=1)

RoundedButton(text="Button1", radius=45, btnbackground="#029510", btnforeground="#ffffff", clicked=func, width=250, height=50).pack(side="left")
RoundedButton(text="Button2", radius=45, btnbackground="#ea4335", btnforeground="#ffffff", clicked=func, width=250, height=50).pack(side="left")
RoundedButton(text="Button3", radius=45, btnbackground="#0078ff", btnforeground="#ffffff", clicked=func, width=250, height=50).pack(side="left")
root.mainloop()

输出:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69090421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档