如何无限调用类

2024-06-02 07:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段无限长的代码。我想把这段代码放在一个类中,在另一个类中定义一个按钮。当按钮被单击时,它应该调用类(代码所在的类),这个类应该像原始代码一样无限地运行。因为我试过好几种方法,我从网上学到的,但一点运气都没有。因为我对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


Tags: 代码importmatplotlibasnpfigplt按钮
1条回答
网友
1楼 · 发布于 2024-06-02 07:07:29

假设您有一个函数do_something,希望在循环中重复调用该函数:

def do_something(...):
    <whatever code you want>

假设您传入一个小部件的引用(例如:root),您可以使用下面的示例连续运行这个函数。在本例中,它每秒钟运行一次代码(例如:1000毫秒)

def run_every_second(root):
    do_something()
    root.after(1000, run_every_second, root)

只需调用run_every_second一次即可启动流程:

root = tk.Tk()
...
run_every_second(root)

我不知道这种方法与matplotlib结合使用是否有效,但是对于普通的tkinter,这是一种非常标准的技术

相关问题 更多 >