1

I'm making a gui for a program i'm creating for a project. I've made multiple buttons in the same row, is it possible to do this in a class so I don't have to keep repeating code? Thanks

flashcards.config(height = 15, width = 45 )
flashcards.place(x=1, y=600)

cMinigames = tk.Button(text="Core Minigames", bg="DarkSeaGreen1", fg="ghost white")
cMinigames.config(height = 15, width = 45)
cMinigames.place(x=300, y=600)

timetables = tk.Button(text="Timetables", bg="DarkSeaGreen1", fg="ghost white")
timetables.config(height = 15, width = 45 )
timetables.place(x=600, y=600)

quizzes = tk.Button(text="Quizzes", bg="DarkSeaGreen1", fg="ghost white")
quizzes.config(height = 15, width = 45 )
quizzes.place(x=900, y=600)

pmf = tk.Button(text="Pick My Focus!", bg="DarkSeaGreen1", fg="ghost white")
pmf.config(height = 15, width = 50 )
pmf.place(x=1200, y=600)```
1
  • for i in range(x):tk.Button().pack() Commented Sep 30, 2020 at 11:52

1 Answer 1

1

Yeah, sure you can. There are multiple ways to create buttons that look alike. One of the ways is creating classes as you've mentioned.

class MyButtons(tk.Button):
    def __init__(self,master,**kwargs):
        super().__init__(master =master, **kwargs)
        self.outlook = {"bg":"DarkSeaGreen1","fg":"ghost white","height":15,"width":45}
        self.config(self.outlook)

If you want to change the background color of the buttons, just change the "bg" option in your self.outlook dictionary. You can also add additional configuration options to the self.outlook dictionary.

After creating the class, you need to create your buttons using that class:

mybutton1 = MyButtons(root,text="Button 1")
mybutton1.place(x=100,y=100)

Another method to create buttons that look alike is using Ttk styles. That is another option. You may want to take a look at that.

Sign up to request clarification or add additional context in comments.

2 Comments

What's the purpose of the "super()" before the init?
It has to do with inheritance. Basicaly what I am doing with super is equivalent to tk.Button.__init__(self,**kwargs). I am initiliazing an instance of tk.Button class. It is about OOP not about tkinter. If you feel you need more information you can look at programiz.com/python-programming/methods/built-in/super and OOP in general.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.