【问题标题】:Is there any way I can resume running by clicking the start button?有什么方法可以通过单击开始按钮来恢复运行?
【发布时间】:2020-10-23 05:36:33
【问题描述】:

我是 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()

【问题讨论】:

  • 我认为你需要将matplotlib后端设置为TkAggimport matplotlib,然后matploblib.use('TkAgg')

标签: python numpy matplotlib tkinter


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助 :D,我尝试了您告诉我修改代码的方法,但反应相同@@
  • 按下开始后,所有按钮都不起作用。也将其添加到问题中
  • 你需要在btn1()的开头加上global running
  • @acw1668 这不是主要问题。更新了答案
  • 根据matplotlib faqmatplotlib 不是线程安全的。
猜你喜欢
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多