Python GUI中的实时绘图 [英] Live Plot in Python GUI
问题描述
我正在尝试编写Python GUI,并且需要进行实时绘制.我目前有一个程序,该程序可以从正在使用的计算机上接收数据,并且希望能够在接收到它们时绘制出机器输出的值.我一直在研究,从到目前为止的发现,在我看来,tkinter或任何库都无法在GUI中做到这一点.有谁知道tkinter是否可以做到这一点以及如何做到这一点,或者是否有另一个图书馆可以进行这样的实时绘图?
I am trying to write a Python GUI and I need to do a live plot. I currently have a program that receives data from a machine I am using and I want to be able to plot the values the machine outputs as I receive them. I have been researching and from what I have found so far, it doesn't seem to me like tkinter or any library can do this in a GUI. Does anyone know whether and how tkinter can do this or if there is another library that is capable of doing such a live plot?
还有,我将如何在收到数据时将收集到的数据写到文件中?
Also, how would I go about writing the data that I gather to a file as I receive the data?
在此先感谢您的帮助.
Thanks in advance for your help.
推荐答案
看起来您是通过轮询获取数据的,这意味着您不需要线程或多个进程.只需在您喜欢的界面上轮询设备并绘制一个点即可.
It looks like you get the data by polling, which means you don't need threads or multiple processes. Simply poll the device at your preferred interface and plot a single point.
这是一个示例,其中包含一些模拟数据来说明总体思想.它每100毫秒更新一次屏幕.
Here's an example with some simulated data to illustrate the general idea. It updates the screen every 100ms.
import Tkinter as tk
import random
class ServoDrive(object):
# simulate values
def getVelocity(self): return random.randint(0,50)
def getTorque(self): return random.randint(50,100)
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.servo = ServoDrive()
self.canvas = tk.Canvas(self, background="black")
self.canvas.pack(side="top", fill="both", expand=True)
# create lines for velocity and torque
self.velocity_line = self.canvas.create_line(0,0,0,0, fill="red")
self.torque_line = self.canvas.create_line(0,0,0,0, fill="blue")
# start the update process
self.update_plot()
def update_plot(self):
v = self.servo.getVelocity()
t = self.servo.getTorque()
self.add_point(self.velocity_line, v)
self.add_point(self.torque_line, t)
self.canvas.xview_moveto(1.0)
self.after(100, self.update_plot)
def add_point(self, line, y):
coords = self.canvas.coords(line)
x = coords[-2] + 1
coords.append(x)
coords.append(y)
coords = coords[-200:] # keep # of points to a manageable size
self.canvas.coords(line, *coords)
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
这篇关于Python GUI中的实时绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!