用用户输入显示每个周期的变化矩阵 [英] Display changing matrix on every cycle with user input

查看:94
本文介绍了用用户输入显示每个周期的变化矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,我想在每次用户输入字符'p'时在当前窗口中像视频流一样显示一个新的随机矩阵

I have a python script where I want to display a new random matrix, in the present window like a video stream, every time a user inputs the character 'p'

import pylab as plt
plt.figure()

matrix = np.zeros((size[0],size[1]))
plt.matshow(matrix)
plt.show()

while(1):
 cmd = raw_input('...')

 if(raw_input == 'p'):
  matrix = get_rand_mat()

 plt.matshow(matrix)
 plt.show()

其中get_rand_mat是某种变态函数,可返回正确尺寸的矩阵

Where get_rand_mat is some arbitary function which returns a matrix of the correct dimensions

但是这里最大的问题是,每次我要获取新的用户输入时都必须关闭图形窗口,然后显示更新的矩阵.

But the big problem here is that I have to close the figure window everytime I want to get new user input and then display the updated matrix.

如何在每次用户输入迭代时更新显示的矩阵,而不必关闭窗口以使程序继续运行?

How can I update the displayed matrix per user input iteration and without having to close a window for the program to progress?

推荐答案

由于matplotlib绘图窗口接管了事件循环,因此在打开窗口时无法从控制台进行输入.

Since the matplotlib plotting window takes over the event loop, the input from the console is not possible while the window is open.

虽然可以使用交互模式(plt.ion()),但这可能会导致其他问题.因此,我的建议是完全在一个现有图形内工作,并将一个事件与 p 的按键相关联.

While it would be possible to use interactive mode (plt.ion()), this might cause other issues. So my suggestion would be to completely work within one existing figure and connect an event to the key press of p.

import matplotlib.pyplot as plt
import numpy as np

size= (25,25)
get_rand_mat = lambda : np.random.rand(*size)

fig = plt.figure()

matrix = np.zeros((size[0],size[1]))
mat = plt.matshow(matrix, fignum=0, vmin=0, vmax=1)

def update(event):
    if event.key == "p":
        matrix = get_rand_mat()
        mat.set_data(matrix)
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("key_press_event", update)

plt.show()

如果运行上述命令并按 p ,则现有图形中将显示一个新的随机矩阵.

If you run the above and press p, a new random matrix is shown within the existing figure.

这篇关于用用户输入显示每个周期的变化矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆