【发布时间】:2017-07-24 04:07:10
【问题描述】:
我设计了一个 GUI 来从文本文件中绘制图形。但是,当我在文本文件中添加新点时,绘图不会更新。我尝试使用 after() 方法继续循环我的函数来绘制图形,但它无法工作。它不会更新我的绘图,甚至不会打印出“正在更新...”,如代码所示。想知道出了什么问题,有没有更好的方法来更新我的情节?谢谢。
class Timer:
def __init__(self, parent):
self.parent = parent
self.time1 = " "
self.time_label = Label(topFrame, text=self.time1, font = "Helvetica 12 bold")
self.time_label.grid(row = 1, column = 1)
self.random_lbl = Label(topFrame, text="Virtual Microgrid", font = "Helvetica 16 bold italic")
self.random_lbl.grid(row = 0, column = 1)
self.random_lbl = Label(topFrame, text="GRAPHS", font = "Helvetica 12 bold" )
self.random_lbl.grid(row = 2, column = 5)
self.update_clock()
def update_clock(self):
self.time2 = time.strftime("%H:%M:%S")
self.time1 = self.time2
self.time_label.config(text=self.time1)
self.parent.after(200, self.update_clock)
def update(self):
self.animate()
print("Updating.....")
self.parent.after(1, self.update)
def animate():
graph_data = open('example.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs.append(x)
ys.append(y)
graph_data = open('example1.txt', 'r').read()
lines = graph_data.split('\n')
xs1 = []
ys1 = []
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs1.append(x)
ys1.append(y)
graph_data = open('example2.txt', 'r').read()
lines = graph_data.split('\n')
xs2 = []
ys2 = []
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs2.append(x)
ys2.append(y)
graph_data = open('example3.txt', 'r').read()
lines = graph_data.split('\n')
xs3 = []
ys3 = []
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs3.append(x)
ys3.append(y)
graph_data = open('example4.txt', 'r').read()
lines = graph_data.split('\n')
xs4 = []
ys4 = []
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs4.append(x)
ys4.append(y)
fig = Figure(figsize=(13,3.25))
a = fig.add_subplot(111)
a.plot(xs,ys,color='red')
a.plot(xs1,ys1,color='blue')
a.plot(xs4,ys4,color='black')
a.set_title ("SOURCE", fontsize=8)
a.set_ylabel("Voltage/V", fontsize=8)
a.set_xlabel("Time/s", fontsize=8)
a.grid()
fig5 = Figure(figsize=(13,3.25))
f = fig5.add_subplot(111)
f.plot(xs2,ys2,color='red')
f.plot(xs3,ys3,color='blue')
f.set_title ("LOAD", fontsize=8)
f.set_ylabel("Voltage/V", fontsize=8)
f.set_xlabel("Time/s", fontsize=8)
f.grid()
canvas = FigureCanvasTkAgg(fig, master=rightFrame)
canvas.get_tk_widget().grid(row = 2, column = 1, sticky = "nswe")
canvas.draw()
canvas5 = FigureCanvasTkAgg(fig5, master=rightFrame)
canvas5.get_tk_widget().grid(row = 3, column = 1, sticky = "nswe")
canvas5.draw()
【问题讨论】:
-
您从未真正调用过
update函数。但是,请注意这样做会导致问题:每次更新都会创建两个全新的人物。相反,您应该创建图形并将它们添加到更新函数外部的画布上。
标签: python python-3.x matplotlib tkinter