python - 有什么方法可以通过单击开始按钮来恢复运行?
问题描述
我是 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()
解决方案
由于您使用的是while running == True
inside btn1()
,因此其他按钮将不起作用,因为程序执行将卡在循环内。您需要为此创建一个线程,以执行您的start
操作,以便其他按钮(以及程序的其余部分)继续正确执行。
推荐阅读
- google-apps-script - 特定 Google 表格标签的 onSelectionChange
- c - 不同编译器中的不同答案
- project-reactor - Java Reactor 在 Mono flatMap 方法中不合适的阻塞方法
- java - 在多个动作事件之间进行选择
- keycloak - 是否可以对用户隐藏 Keycloak 的界面?
- python-3.x - 如何调用返回 plotly fig 对象的函数或 def 并通过单击按钮在另一个 plotly 中更新它
- django-rest-framework - ESP8266 在 Django webapp 中的 POST 请求上返回代码 400
- python - 如何在for循环中匹配以特定字母序列开头的所有单词?(Python)
- r - R:手动排序 X 轴数据时的堆积条形图错误 (ggplot2)
- reactjs - 我怎样才能比我的 axios 命令更快地更新状态?