python tkinter mainloop,如何在tkinter mainloop()中使用函数

我决定试试Python,到目前为止它还很有趣。然而,在和tkinter混在一起的时候,我遇到了一个几个小时都没能解决的问题。我读过一些东西,尝试过不同的东西,但都没用。

到目前为止,我已经得到了代码,我认为程序应该可以正常运行。除了我不能让它循环从而自动更新。在

所以我的问题是:如何以一种中缀循环方式调用带有tkinters循环选项的函数?

简单的生活游戏:

我基本上写了2节课。存储和处理单个单元格的矩阵

而游戏本身就是通过一些游戏逻辑和基本的用户输入来利用矩阵类。在

首先是游戏类,因为我的循环问题:from tkinter import *

from ButtonMatrix import *

class Conway:

def __init__(self, master, size = 20, cell_size = 2):

self.is_running = True

self.matrix = ButtonMatrix(master,size,cell_size)

self.matrix.randomize()

self.matrix.count_neighbours()

self.master = master

# playbutton sets boolean for running the program in a loop

self.playbutton = Button(master, text = str(self.is_running), command = self.stop)

self.playbutton.grid(row = 0 , column = size +1 )

#Test button to trigger the next generation manually. Works as itended.

self.next = Button(master, text="next", command = self.play)

self.next.grid(row = 1, column = size +1)

def play(self): # Calculates and sets the next generation. Intended to be used in a loop

if self.is_running:

self.apply_ruleset()

self.matrix.count_neighbours()

self.apply_colors()

def apply_ruleset(self):

#The ruleset of conways game of life. I wish i knew how to adress each element

#without using these two ugly loops all the time

size = len(self.matrix.cells)

for x in range (size):

for y in range (size):

if self.cell(x,y).is_alive():

if self.cell(x,y).neighbours < 2 or self.cell(x,y).neighbours > 3:

self.cell(x,y).toggle()

if not self.cell(x,y).is_alive() and self.cell(x,y).neighbours == 3:

self.cell(x,y).toggle()

def apply_colors(self): #Some flashy colors just for fun

size = len(self.matrix.cells)

for x in range (size):

for y in range (size):

if self.cell(x,y).is_alive():

if self.cell(x,y).neighbours < 2 or self.cell(x,y).neighbours > 3:

self.cell(x,y).button.configure(bg = "chartreuse3")

if not self.cell(x,y).is_alive() and self.cell(x,y).neighbours == 3:

self.cell(x,y).button.configure(bg = "lightgreen")

def cell(self,x,y):

return self.matrix.cell(x,y)

def start (self): #start and stop set the boolean for the loop. They work and switch the state properly

self.is_running = True

self.playbutton.configure(text=str(self.is_running), command =self.stop)

def stop (self):

self.is_running = False

self.playbutton.configure(text=str(self.is_running), command =self.start)

#Test program. I can't make the loop work. Manual update via next button works however

root = Tk()

conway = Conway(root)

root.after(1000, conway.play())

root.mainloop()

矩阵(仅限感兴趣的读者):

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值