我正在使用Tkinter制作可伸缩的井字游戏程序。当我按下一个空的方形按钮时,图像会发生变化。当我按下另一个按钮时,第一次按下的按钮中的图像会完全消失,而我希望它保持不变,唯一带有X / O图像的按钮就是最后按下的按钮。对解决此问题有帮助吗?我是初学者。
如果您还具有如何进行可伸缩的获胜支票的任何技巧(使用可伸缩的意思是用户可以输入从2x2到适合屏幕大小的木板尺寸,那将非常有帮助。
[这里是我使用的图像,如果有用的话(链接可以使用24小时,它们只是框的基本125x125图像,X和O)https://picresize.com/b5deea04656747
from tkinter import *
class XOGame:
def main_game(self):
self.__game_window = Tk()
self.__grid_size = 3 # User inputted in a different part of the code
self.__game_window.title("Tic Tac Toe (" + str(self.__grid_size) + "x"
+ str(self.__grid_size) + ")")
self.build_board(self.__game_window)
self.__game_window.mainloop()
def build_board(self, window):
self.__size = self.__grid_size ** 2
self.__empty_square = PhotoImage(master=window,
file="rsz_empty.gif")
self.__squares = [None] * self.__size
# Building the buttons and gridding them
for i in range(self.__size):
self.__squares[i] = (Button(window, image=self.__empty_square))
row = 0
column = 0
number = 1
for j in self.__squares:
j.grid(row=row, column=column)
j.config(command=lambda index=self.__squares.index(j):
self.change_mark(index))
column += 1
if number % 3 == 0:
row += 1
column = 0
number += 1
# This is the part where the picture changing happens.
# I have yet to implement the turn system, thus self.__x being the only image being configured.
# This is the part with the issue.
def change_mark(self, i):
self.__x = PhotoImage(master=self.__game_window,
file="rsz_cross.gif")
self.__o = PhotoImage(master=self.__game_window,
file="rsz_nought.gif")
self.__squares[i].configure(image=self.__x, state=DISABLED)
def start(self):
# Function starts the first window of the game.
self.main_game()
def main():
ui = XOGame()
ui.start()
main()
问题:首先按下的按钮中的图像完全消失
您每次单击都会覆盖self.__x = PhotoImage(...
,这会导致前一张图像的垃圾收集,并且tkinter
会松开图像参考。
创建图像仅一次,然后像self.empty_square
一样重复使用。
简化为以下内容:
def build_board(self, window):
self.empty_square = PhotoImage(master=window, file="empty.gif")
self.x_square = PhotoImage(master=window, file="cross.gif")
self.squares = []
for row in range(3):
for column in range(3):
self.squares.append(Button(window, image=self.empty_square))
self.squares[-1].grid(row=row, column=column)
self.squares[-1].bind("<Button-1>", self.change_mark)
def change_mark(self, event):
w = event.widget
w.configure(image=self.x_square, state=DISABLED)