Python Tkinter按钮命令重置变量

时间:2019-05-02 02:21:42

标签: python-3.x tkinter

所以我正在尝试编写井字游戏。我试图在按下按钮后更新值。每按一次按钮,更新不会停留,并且会重置。我绝对很沮丧,我是一个初学者,所以请向我解释为什么我需要在main()方法以及on_click方法中将turn声明为global。

还简要说明了lambda:inx = count:on_click(inx)为何起作用,但是lambda:on_click(count)为何不起作用。

任何帮助该代码更好地工作或变得更有道理的提示都是很棒的。我也不习惯使用类,这就是所有功能的原因。尚不确定何时何地使用类。

我已经尝试了所有可以解决的问题,但我无法解决。

    import tkinter


    def on_click(inx):
        buttonfont = ('helvetica', 100, 'bold')
        global turn
        turn += 1
        spot = {}

        if turn % 2 == 0:
            buttons[inx].configure(text='O', width=200, height=200, compound='center', state='disabled', font=buttonfont, disabledforeground='blue')
            spot.update({inx: 'O'})
        else:
            buttons[inx].configure(text='X', width=200, height=200, compound='center', state='disabled', font=buttonfont, disabledforeground='red')
            spot.update({inx: 'X'})


    def create_window_and_buttons():
        game_window = tkinter.Tk()
        game_window.title('Tic-Tac-Toe')
        for i in range(0, 3):
            game_window.rowconfigure(i, weight=1)
            game_window.columnconfigure(i, weight=1)
        game_window.geometry('600x600')
        global pixel
        pixel = tkinter.PhotoImage(width=1, height=1)
        count = 0
        for i in range(3):
            for j in range(3):
                buttons.append(tkinter.Button(game_window, image=pixel, width=200, height=200, command=lambda inx=count:
                                              on_click(inx)))
                buttons[count].grid(row=i, column=j, sticky='NSEW')
                count += 1

        return game_window


    def main():
        global turn
        turn = 0
        global buttons
        buttons = []
        game_window = create_window_and_buttons()
        game_window.mainloop()


    if __name__ == '__main__':
        main()

我希望它更新字典,然后继续添加值,但是每次都会重置。在main()和on_click()中将turn变量设置为global之前,turn变量也存在相同的问题。

1 个答案:

答案 0 :(得分:1)

您每次执行spot时都会重置on_click字典。只需将其移至主要功能之外即可:

import tkinter

spot = {}

def on_click(inx):
   buttonfont = ('helvetica', 100, 'bold')
   global turn
   turn += 1
   #spot = {}
   ...

关于lambda: on_click(count)为何无法按预期工作的原因,这是由于Python的闭包被后期绑定,您可以阅读here