为什么Tk()。只执行一次后如何解决?
我尝试在.after()
内重新运行tick()
,但如果我取消注释该行,则根本不会显示该窗口。
使用Windows 8.1和Python 3
import tkinter as tk
def tick():
matrix_size = board.get_matrix_size()
alive_neighbours = [[None] * matrix_size for i in range(matrix_size)]
for row in range(matrix_size):
for col in range(matrix_size):
alive_neighbours[row][col] = get_alive_neighbours(row, col)
for row in range(matrix_size):
for col in range(matrix_size):
if alive_neighbours[row][col] == 3:
board.create_cell(row, col)
elif alive_neighbours[row][col] < 2:
board.kill_cell(row, col)
elif alive_neighbours[row][col] == 2 and board.get_cell_state(row, col) == "alive":
continue
elif alive_neighbours[row][col] > 3:
board.kill_cell(row, col)
# root.after(1000, tick())
def get_alive_neighbours(row, col):
alive_neighbour_count = 0
for relative_row in range(-1, 2): # Top cells
for relative_col in range(-1, 2):
if relative_row == 0 and relative_col == 0:
continue # Do not current cell as neighbour
else:
cell_state = board.get_cell_state(row + relative_row, col + relative_col)
if cell_state == "alive":
alive_neighbour_count += 1
return alive_neighbour_count
class GameBoard(tk.Frame):
matrix_size = 10
grid_size = 32
matrix = []
alive_color = "white"
dead_color = "grey"
def __init__(self, master=None):
self.matrix = [[None] * self.matrix_size for i in range(self.matrix_size)]
canvas_width = self.matrix_size * self.grid_size
canvas_height = self.matrix_size * self.grid_size
tk.Frame.__init__(self, master)
self.canvas = tk.Canvas(self, width=canvas_width, height=canvas_height)
self.draw_board()
self.initialize_cells()
self.canvas.grid()
def draw_board(self):
color = "white"
for row in range(len(self.matrix)):
for col in range(len(self.matrix[row])):
# color = "white" if (col+row)%2==0 else "lightgrey"
color = "lightgrey"
x0 = (col * self.grid_size + 2) # Why +2?
y0 = (row * self.grid_size + 2) # Why +2
x1 = x0 + self.grid_size
y1 = y0 + self.grid_size
id = self.canvas.create_rectangle(x0, y0, x1, y1, fill=color, width=0)
self.matrix[row][col] = id
def create_cell(self, row, column):
grid_item = self.matrix[row][column]
self.canvas.itemconfigure(grid_item, fill=self.alive_color)
def kill_cell(self, row, column):
grid_item = self.matrix[row][column]
self.canvas.itemconfigure(grid_item, fill=self.dead_color)
def get_cell_state(self, row, column):
try:
grid_item = self.matrix[row][column]
except IndexError:
return "dead"
else:
fill_color = self.canvas.itemcget(grid_item, "fill")
if fill_color == "white":
return "alive"
else:
return "dead"
def get_matrix(self):
return self.matrix
def get_matrix_size(self):
return self.matrix_size
def initialize_cells(self):
self.create_cell(1, 1)
self.create_cell(1, 2)
self.create_cell(2, 1)
self.grid()
if __name__ == "__main__":
root = tk.Tk()
root.resizable(0, 0)
board = GameBoard(master=root)
root.after(1000, tick())
root.mainloop()
答案 0 :(得分:2)
问题在于,当您将这些方法用作参数时,您调用方法,因此使用tick
函数(None
)的返回值。
取消注释您提及的行,并将您的after
来电替换为
root.after(1000, tick)
因此,您正在传递tick
函数本身。