1

I've been working on python recently and wanted to make a program using tkinter to form a very basic GUI for a tic-tac-toe game. When I was assigning the command property of a button to a function that would then change the text of the button (ie from the button saying 'Top Right' to saying 'x' because a player took the space). When I run the program however, the command is instantly ran and I cannot find a reason for it to.

Why is the program running this function on launch and is there a better way to write this so it doesn't end up doing the same thing?

from tkinter import *

class Application(Frame):

    def __init__(self, master= None):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.TopL = Button(self, text='Top Left')
        self.TopL['command'] = self.test(self.TopL)
        self.TopC = Button(self, text='Top Center')
        self.TopR = Button(self, text='Top Right')
        self.MidL = Button(self, text='Middle Left')
        self.MidC = Button(self, text='Middle Center')
        self.MidR = Button(self, text='Middle Right')
        self.BotL = Button(self, text='Bottom Left')
        self.BotC = Button(self, text='Bottom Center')
        self.BotR = Button(self, text='Bottom Right')

        self.TopL.grid(column=0, row=1)
        self.TopC.grid(column=1, row=1)
        self.TopR.grid(column=2, row=1)

        self.MidL.grid(column=0, row=2)
        self.MidC.grid(column=1, row=2)
        self.MidR.grid(column=2, row=2)

        self.BotL.grid(column=0, row=3)
        self.BotC.grid(column=1, row=3)
        self.BotR.grid(column=2, row=3)

        self.QUIT = Button(self, text='QUIT')
        self.QUIT['command'] = self.quit()
        self.QUIT.grid(row=0)

    def test(self, button):
        button['text'] = 'x'
    def update(self, button, player_letter):
        pass

app = Application()
app.master.title('Tic Tac Toe')
app.mainloop()
Ben Wagner
  • 11
  • 1
  • Try `self.TopL['command'] = lambda: self.test(self.TopL)` – Constantly Confused Dec 16 '15 at 17:38
  • Why is the program running this function on launch--> A common problem, .i.e remove the "()" as it causes the function to run immediately--self.QUIT['command'] = self.quit()<---delete these –  Dec 16 '15 at 17:59

0 Answers0