首页 > 解决方案 > 有什么方法可以通过单击开始按钮来恢复运行?

问题描述

我是 Python 新手。我在代码中有三个按钮: 第一个是开始运行图表,第二个是停止运行。但是,如果我想在再次按下按钮时恢复运行,我不知道该怎么办start。一旦我按下start按钮,所有按钮都不起作用。

import matplotlib.pyplot as plt
import numpy as np
import tkinter

running=True
def btn1():
    plt.clf()
    while running==True:       
        x=np.arange(1,51)
        f=np.random.choice(x,15,replace=True, p=None)
        x_pos = [i for i, _ in enumerate(f)]
        plt.bar(x_pos, f, color='green')
        print(f)
        plt.xticks(x_pos, x)
        plt.plot()
        plt.pause(0.5)
    plt.ioff()
    plt.show()

def stop():

    global running
    running = False
    

def closewindow():
     window.destroy()
    

window = tkinter.Tk()
screensize = 500, 500
size = str(screensize[0])+'x'+str(screensize[1])
window.geometry(size)

but1 = tkinter.Button(window, text="start", command=btn1).grid(column = 1, row = 1)
but2=tkinter.Button(window, text="end", command=stop).grid(column = 1, row =2)
ext = tkinter.Button(window, text="exit", command=closewindow).grid(column = 1, row =3 )
window.mainloop()

标签: pythonnumpymatplotlibtkinter

解决方案


由于您使用的是while running == Trueinside btn1(),因此其他按钮将不起作用,因为程序执行将卡在循环内。您需要为此创建一个线程,以执行您的start操作,以便其他按钮(以及程序的其余部分)继续正确执行。


推荐阅读