0

I want a rounded button like on the image

button rounded

and change de color of the background the button without class (I don't know how to use a class if you teach me I can use it too) with python tkinter. I have tried

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

and I get an error NameError: name 'CustomButton' is not defined

This is my code

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

j_4321
  • 15,431
  • 3
  • 34
  • 61
Gaby
  • 3
  • 6
  • this is my code if you is talking to `button = CustomButton(window, 100, 25, 'red') ` i get in here https://stackoverflow.com/questions/42579927/rounded-button-tkinter-python – Gaby Sep 07 '21 at 15:03
  • 1
    The `NameError` appears because you haven't defined `CustomButton` inside your script. Try copy/pasting the class from the question you linked. Also please look at some basic python tutorials. – TheLizzard Sep 07 '21 at 15:12

2 Answers2

1

You need to include that class in your file or in a separate file and then import it.

here is an example (The rounded button is taken from 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()

Output: enter image description here

Art
  • 2,836
  • 4
  • 17
  • 34
0

The problem is, that you are using a class created by someone else and did not include it in your code. The CustomButton-class needs to be included on the top of your file.

I would really urge you to read up on classes. Object-oriented-programming is the basis of python and how to write more complex code.

DeerFreak
  • 105
  • 6