当前位置: 首页 > 知识库问答 >
问题:

如何在tkinter中更新、暂停和清除画布

上官和韵
2023-03-14

我正在尝试用python、matplotlib、numpy和tkinter创建生活游戏。在用户输入行数、列数和生成活动单元格的概率后,用户将按下“生成”按钮开始游戏。我可以显示第一个画布,但除此之外,程序似乎无法更新画布。更新时(使用while循环),我希望程序首先调用更新画布的函数,然后暂停图形0.5秒,最后清除画布,以便显示下一个更新的画布。我似乎对FigureCanvasTkAgg有最大的问题(我对tkinter很陌生),因为它似乎不接受pause和delete属性。是否有其他方法可以更新、暂停和清除画布?以下是我的代码:

from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from board import Board
from PIL import Image, ImageTk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
import time

iteration = 0
def num():
    global iteration
    iteration += 1
    n1 = int(t1.get())
    n2 = int(t2.get())
    n3 = int(t3.get()) / 100.00
    initBoard = np.zeros((n1, n2))
    for row in range(0,n1):
            for column in range(0,n2):
                initBoard[row][column] = np.random.choice(np.arange(0, 2), p = [1 - n3, n3])
    game_board = Board(n1, n2, initBoard)
    user_input = ''
    while user_input != 'q':
        if user_input == '':
            game_board.update_board()
            ax.imshow(initBoard)
            canvas.draw_idle()
            ax.delete('all')

root = Tk()
root.title('Game of Life')
root.geometry('800x600')

#top = Toplevel(root)
Label(root, text="How many rows?: ").grid(row = 0)
Label(root, text="How many columns?: ").grid(row = 1)
Label(root, text="Probability of spawn (between 0 and 100): ").grid(row = 2)

t1 = Entry(root)
t2 = Entry(root)
t3 = Entry(root)

t1.grid(row = 0, column = 1)
t2.grid(row = 1, column = 1)
t3.grid(row = 2, column = 1)

Button(root, text = 'Generate', command = num).grid(row = 3, column = 1, sticky = W, pady = 4)

fig= plt.figure()
ax = fig.add_subplot(111)
ax.axis('off')
canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().grid(row = 4, column = 0)

mainloop()


以下是Board和update\u Board()导致的结果:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
import matplotlib.animation as animation
from tkinter import *

class Board:
    def __init__(self, rows, columns, game_board):
        self.rows = rows
        self.columns = columns
        self.initBoard = game_board
    
    def update_board(self):
        for row in range(0, self.rows):
            for column in range(0, self.columns):
                check_neighbour = self.check_neighbour(row, column)
                living_neighbours_count = 0
                for neighbour_cell in check_neighbour:
                    if neighbour_cell == 1:
                        living_neighbours_count += 1
                
                if self.initBoard[row][column] == 1:
                    if living_neighbours_count < 2 or living_neighbours_count > 3:
                        self.initBoard[row][column] = 0
                else:
                    if living_neighbours_count == 3:
                        self.initBoard[row][column] = 1

    def check_neighbour(self, check_row, check_column):
        search_min = -1
        search_max = 2
        neighbour_list = []
        for row in range(search_min, search_max):
            for column in range(search_min, search_max):
                neighbour_row = check_row + row
                neighbour_column = check_column + column

                valid_neighbour = True

                if (neighbour_row) == check_row and (neighbour_column) == check_column:
                    valid_neighbour = False

                if (neighbour_row) < 0 or (neighbour_row) >= self.rows:
                    valid_neighbour = False

                if (neighbour_column) < 0 or (neighbour_column) >= self.columns:
                    valid_neighbour = False

                if valid_neighbour:
                    neighbour_list.append(self.initBoard[neighbour_row][neighbour_column])
        return neighbour_list

共有1个答案

卞云瀚
2023-03-14

我不是很肯定,但我认为下面是你想要的。我每500毫秒就有明显的变化,所以,这肯定是一个进步。我不得不重写/重新格式化你的主要部分。这是一个大烂摊子,所以我把它清理干净了。

import numpy as np
import tkinter as tk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image, ImageTk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

class Board:
    def __init__(self, rows, columns, game_board):
        self.rows = rows
        self.columns = columns
        self.initBoard = game_board
    
    def update_board(self):
        for row in range(0, self.rows):
            for column in range(0, self.columns):
                check_neighbour = self.check_neighbour(row, column)
                living_neighbours_count = 0
                for neighbour_cell in check_neighbour:
                    if neighbour_cell == 1:
                        living_neighbours_count += 1
                
                if self.initBoard[row][column] == 1:
                    if living_neighbours_count < 2 or living_neighbours_count > 3:
                        self.initBoard[row][column] = 0
                else:
                    if living_neighbours_count == 3:
                        self.initBoard[row][column] = 1

    def check_neighbour(self, check_row, check_column):
        search_min = -1
        search_max = 2
        neighbour_list = []
        for row in range(search_min, search_max):
            for column in range(search_min, search_max):
                neighbour_row = check_row + row
                neighbour_column = check_column + column

                valid_neighbour = True

                if (neighbour_row) == check_row and (neighbour_column) == check_column:
                    valid_neighbour = False

                if (neighbour_row) < 0 or (neighbour_row) >= self.rows:
                    valid_neighbour = False

                if (neighbour_column) < 0 or (neighbour_column) >= self.columns:
                    valid_neighbour = False

                if valid_neighbour:
                    neighbour_list.append(self.initBoard[neighbour_row][neighbour_column])
        
        return neighbour_list
        
        
class App(tk.Tk):
    WIDTH  = 800
    HEIGHT = 600
    TITLE  = 'Game Of Life'

    def __init__(self, **kwargs):
        tk.Tk.__init__(self, **kwargs)

        self.iteration=0
        self.fig = plt.figure()
        self.ax  = self.fig.add_subplot(111)
        self.ax.axis('off')
        
        tk.Label(self, text="How many rows?: ").grid(row=0)
        tk.Label(self, text="How many columns?: ").grid(row=1)
        tk.Label(self, text="Probability of spawn (between 0 and 100): ").grid(row=2)
        
        self.t1 = tk.Entry(self)
        self.t2 = tk.Entry(self)
        self.t3 = tk.Entry(self)
        
        self.t1.grid(row=0, column=1)
        self.t2.grid(row=1, column=1)
        self.t3.grid(row=2, column=1)
        
        tk.Button(self, text='Generate', command=self.plot).grid(row=3, column=1, sticky='w', pady=4)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self)  # A tk.DrawingArea.
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=4, column=0)
        
    def plot(self):
        n1 = int(self.t1.get())
        n2 = int(self.t2.get())
        n3 = int(self.t3.get()) / 100.00
        self.initBoard = np.zeros((n1, n2))
    
        for row in range(0,n1):
            for column in range(0,n2):
                self.initBoard[row][column] = np.random.choice(np.arange(0, 2), p = [1 - n3, n3])
        
        self.game_board = Board(n1, n2, self.initBoard)
        self.update()
        
    def update(self):
        self.game_board.update_board()
        self.ax.imshow(self.initBoard)
        self.canvas.draw_idle()
        self.after(500, self.update)
        
        
if __name__ == '__main__':
    app = App()
    app.title(App.TITLE)
    app.geometry(f'{App.WIDTH}x{App.HEIGHT}')
    app.mainloop()
 类似资料:
  • 我的第一个ionic网络应用程序有问题。我应该做一些图表,所以我决定使用d3.js和tree.js。我增加了用不同类型的图表可视化我的数据的可能性。当我在同一个画布上绘制不同的图表时,问题出现了,所以我想我必须在每次更新之前清除画布。这是我的代码: 在网络上搜索(如何清除画布以进行重绘),我试图添加以下行: 但是我仍然有问题。 演示我的问题 你能帮我吗?谢了。

  • 问题内容: 在尝试了复合操作并在画布上绘制图像之后,我现在尝试删除图像并进行合成。我该怎么做呢? 我需要清除画布才能重画其他图像;这可能会持续一段时间,所以我认为每次绘制一个新矩形都不是最有效的选择。 问题答案:

  • 我正在尝试清除JavaFX中的简单画布。 启动功能 如果用户想要加载游戏,则loadSave布尔变量集为“true” 否则,它会加载新游戏 我真的很感激你的帮助。

  • 问题内容: 我试图谷歌,并从这个论坛上寻找我的问题的解决方案,但到目前为止没有运气。我想通过单击图片来暂停CSS3动画(图像幻灯片放映),并通过单击图片来恢复到相同的动画。 我知道如何暂停幻灯片放映,我也能够将其恢复一次,但是如果尝试暂停并恢复多次以上,它将停止工作。这是我的代码的样子: 我不想使用任何JS库(例如jQuery)或任何其他外部解决方案。 我的猜测是我的函数内部的函数仍在运行,这就是

  • 我有一个小游戏,当用户按下暂停按钮时,我需要暂停计时器,然后恢复计时器,并在用户按下恢复按钮时继续增加秒数。我研究了很多,我尝试了不同的解决方案,但没有一个对我有效。你能帮我实现这个功能吗?下面是我的代码: 谢谢你读这篇文章。

  • 问题内容: 因此,我有一堂课,必须编写程序来制作Simon。我知道我的做法不一定是最好的方法,但是,他有一些晦涩的要求,所以这就是我这样做的原因。 我的程序即将完成,但是有一个主要问题。当我按下重设”按钮时,我调用了一种称为“重设”的方法,该方法又将计算机设置为 播放其第一步。 在此期间,将进行图形更新。 当我自己调用reset方法时,它可以按预期工作。当我按下reset按钮时,它会执行所有图形更