I'm trying to create a GUI using tkinter in Python3 which will have several buttons and I dont want to type the same attributes for all of them each time like this:
tkinter.Button(topFrame, font=("Ariel", 16), width=10, height=10,
fg="#ffffff", bg="#000000", text="Cake")
For example, fg
, bg
colour and size
will all be the same on each button. The only things changing on each button will be the text and where on the screen to put them.
I'm quite new to programming and Python and am trying to re-use code when I want to create a new button. I think I'm missing some understanding of classes which I'm not getting when I read up on it.
I want to pass in different text for each button and a different frame in order to place it in a different location on the GUI and have everything else the same.
My code so far:
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
#create default values for buttons
#frame and buttonText are the values passed to the class when making a new
#button
class myButtons:
def buttonLayout(self, frame, buttonText):
self.newButton=tkinter.Button(frame, font=("Ariel", 16),
width=10, height=10, fg=#ffffff,
bg=#000000, text=buttonText)
topFrame = tkinter.Frame(window)
topFrame.pack()
#create new button here and place in the frame called topFrame with the text
#"Cake" on it
buttonCake = myButtons.buttonLayout(topFrame, "Cake")
#position the new button in a certain cell using grid in topFrame
buttonCake.grid(row=1, column=0)
window.mainloop()
The error I get when I try to run it is:
TypeError: buttonLayout() missing 1 required positional argument: 'buttonText'
I'm confused because I'm passing in "Cake"
and the error says it's missing.
Thank you for pointing out init I was not aware of how to use init for my problem, but that and the answers given here have helped. Thank you.