我有这段无限运行的代码。我想把这段代码放在一个类中,并在另一个类中定义一个按钮。当按钮被点击时,它应该调用类(代码在其中),这个类应该像原始代码一样无限运行。由于我尝试了几种从互联网上学到的方法,但都没有运气。因为我对python完全陌生。任何帮助,将不胜感激。如何无限地调用一个类
import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
import matplotlib.animation as animation
j=0
fig = plt.figure()
ax1 = fig.add_axes([0.85, 0.093, 0.04, 0.8])
cax = fig.add_subplot(1, 1, 1)
H = np.array([[1, 2, 3, 1], [4, 5, 6, 10], [3, 7, 8, 4], [10, 5, 3, 1]])
Z = np.array([[3, 290, 600], [1011, 230, 830], [152, 750, 5]])
def func(i):
global j
if j == 0:
j += 1
rows, cols = H.shape
im = plt.imshow(H, interpolation='nearest',
extent=[0, cols, 0, rows],
cmap='bwr', vmin=0, vmax=10)
fig.colorbar(im, cax=ax1, orientation='vertical')
elif j == 1:
j -= 1
rows, cols = H.shape
im = plt.imshow(Z, interpolation='nearest', cmap='Spectral', vmin=0, vmax=1023,
extent=[0, cols, 0, rows])
v = np.linspace(0, 1023, 15, endpoint=True)
fig.colorbar(im, cax=ax1, orientation='vertical', ticks=v)
ani = animation.FuncAnimation(fig, func, interval=1000)
plt.show()
应该更好地使用Canvas
而不是imshow
因为后来我将一个GUI,使用Tkinter的。
您可以在Tkinter中嵌入图表,假设这是您点击按钮时更新/更改它的其他课程。 – Pythonista