我刚开始在 Python(3.2) 中使用 Tkinter 模块,所以我决定用这个模块重写我的旧程序(我使用 curses 模块)。该程序是一个生命游戏模拟器。我实现的算法在没有用户界面的情况下运行得如此之快。这是我的程序(这是一个快速的实验,我从未使用过画布小部件):
#!/usr/bin/python3
import gol
import Tkinter as tk
class Application(tk.Frame):
def __init__(self):
self.root = tk.Tk()
self.root.wm_title('Canvas Experiments')
tk.Frame.__init__(self, self.root)
self.draw_widgets()
self.world = gol.World(30, 30)
self.world.cells[25][26] = True
self.world.cells[26][26] = True
self.world.cells[27][26] = True
self.world.cells[25][27] = True
self.world.cells[26][28] = True
def draw_widgets(self):
self.canvas = tk.Canvas(
width = 300,
height = 300,
bg = '#FFF')
self.canvas.grid(row = 0)
self.b_next = tk.Button(
text = 'Next',
command = self.play)
self.b_next.grid(row = 1)
self.grid()
def play(self):
def draw(x, y, alive):
if alive:
self.canvas.create_rectangle(x*10, y*10, x*10+9, y*10+9, fill='#F00')
else:
self.canvas.create_rectangle(x*10, y*10, x*10+9, y*10+9, fill='#FFF')
for y in range(self.world.width):
for x in range(self.world.height):
draw(x, y, self.world.cells[x][y])
self.world.evolve()
app = Application()
app.mainloop()
我没有报告 gol,但问题不在该模块中。问题是程序很慢,我认为我不能很好地使用画布。
编辑:这是 gol 模块,但我认为这不是问题......
#!/usr/bin/python3
class World:
def __init__(self, width, height):
self.width, self.height = width, height
self.cells = [[False for row in range(self.height)] for column in range(self.width)]
def neighbours(self, x, y):
counter = 0
for i in range(-1, 2):
for j in range(-1, 2):
if ((0 <= x + i < self.width) and (0 <= y + j < self.height) and not (i == 0 and j == 0)):
if self.cells[x + i][y + j]:
counter += 1
return counter
def evolve(self):
cells_tmp = [[False for row in range(self.height)] for column in range(self.width)]
for x in range(self.width):
for y in range(self.height):
if self.cells[x][y]:
if self.neighbours(x, y) == 2 or self.neighbours(x, y) == 3:
cells_tmp[x][y] = True
else:
if self.neighbours(x, y) == 3:
cells_tmp[x][y] = True
self.cells = cells_tmp