0

I'm new to tkinter and I want to know how to get the value of the button's background color or change the value of the button's background color.

This is for a school project and I'm trying to make a working checkerboard.

Code

import tkinter as tk

class Checkers(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.button = tk.Button(
            self, width=32, height=35, 
            background='black', command=self.movebutton()
        ).grid(row=2, column=1, sticky=tk.W)

    def movebutton(self):
        if self.button['bg'] == 'black':
            self.button = tk.Button(
                self, width=4, height=2, background='red4'
            ).grid(row=2, column=1, sticky=tk.W)

root = tk.Tk()
root.title("Checkers")
root.geometry("600x400")
app = Checkers(root)
root.mainloop()

I wanted for a red square to replace the black one but I'm getting an error "AttributeError: 'Checkers' object has no attribute 'button'"

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

1

Your error is caused by line 12 and 13 where you wrote command=self.movebutton(). It should just be command=self.movebutton. For the command option, you are to reference the function you want to execute instead of executing it. Putting () symbol after the function name means you are executing(not referencing) the function. It is an error because while creating the attribute self.button (i.e. tkinter has yet to create it), you are also executing a function that uses self.button.

Sun Bear
  • 7,594
  • 11
  • 56
  • 102