使用tkinter时发出处理按钮单击

时间:2015-12-16 17:17:21

标签: python python-3.x tkinter

我最近一直在研究python,并希望使用tkinter创建一个程序,为tic-tac-toe游戏构建一个非常基本的GUI。当我将一个按钮的命令属性分配给一个函数时,该函数随后会改变按钮的文本(即从“右上角”按钮到“x”因为玩家占用空间而改变)。然而,当我运行程序时,命令立即运行,我找不到它的原因。

为什么程序在启动时运行这个函数,是否有更好的方法来编写它,所以它最终不会做同样的事情?

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

0 个答案:

没有答案