PySimpleGUI画动态图的代码?
时间: 2023-07-03 20:23:36 浏览: 164
使用pyqt5实现的Python-GUI动态作图例子
5星 · 资源好评率100%
以下是使用PySimpleGUI绘制动态图的示例代码:
```python
import PySimpleGUI as sg
import random
# 定义GUI布局
layout = [[sg.Graph(canvas_size=(400, 400), graph_bottom_left=(0, 0), graph_top_right=(400, 400), background_color='white', key='graph')],
[sg.Button('Start'), sg.Button('Stop'), sg.Exit()]]
# 创建GUI窗口
window = sg.Window('Animated Graph', layout)
# 初始化绘图数据
points = [(x, random.randint(0, 400)) for x in range(400)]
line = None
# 动态绘制
while True:
event, values = window.read(timeout=100)
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Start':
line = window['graph'].draw_line(points, width=2, color='red')
elif event == 'Stop':
window['graph'].delete_figure(line)
line = None
if line:
# 更新绘图数据
points.pop(0)
points.append((399, random.randint(0, 400)))
# 重新绘制线条
window['graph'].delete_figure(line)
line = window['graph'].draw_line(points, width=2, color='red')
# 刷新GUI窗口
window.refresh()
# 关闭GUI窗口
window.close()
```
运行以上代码,会打开一个窗口,点击Start按钮可以开始绘制动态图,点击Stop按钮可以停止绘制,点击Exit按钮可以退出程序。在本例中,我们使用PySimpleGUI的Graph组件来绘制图形,并通过循环不断更新绘图数据,实现动态绘制的效果。
阅读全文