【问题标题】:How to use a padding to rounded button on tkinter如何在 tkinter 上使用填充圆角按钮
【发布时间】:2021-09-07 14:54:01
【问题描述】:

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

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

button = CustomButton(window, 100, 25, 'red') 

我收到一个错误NameError: name 'CustomButton' is not defined

这是我的代码

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

【问题讨论】:

  • 这是我的代码,如果你正在和 button = CustomButton(window, 100, 25, 'red') 交谈,我会进入这里 stackoverflow.com/questions/42579927/…
  • NameError 出现是因为您尚未在脚本中定义 CustomButton。尝试从您链接的问题中复制/粘贴课程。另外请看一些基本的python教程。

标签: python user-interface tkinter


【解决方案1】:

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

我真的会敦促您阅读课程。面向对象编程是python的基础以及如何编写更复杂的代码。

【讨论】:

  • 我会在导入之后加入该类,因为我认为这是最佳实践的一部分。
  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
【解决方案2】:

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

这里是一个例子(圆形按钮取自here):

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

输出:

【讨论】:

    猜你喜欢
    • 2019-08-15
    • 1970-01-01
    • 2019-12-28
    • 2021-08-25
    • 2011-07-06
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2022-08-14
    相关资源
    最近更新 更多