user interface - Unable to update TKinter graph -


colleagues,

i designing gui 2 buttons , 1 display graph, hourly temperature. issue facing can not make function(update_graph) updates value self.after.

this part creates page 1 , working fine, until call update_graph

class pageone(tk.frame):      def __init__(self, parent, controller):         tk.frame.__init__(self, parent)         label = tk.label(self, text="page one!!!", font=large_font)         label.pack(pady=10,padx=10)          button1 = tk.button(self, text="back home",                             command=lambda: controller.show_frame(startpage))         button1.pack()          button2 = tk.button(self, text="page two",                             command=lambda: controller.show_frame(pagetwo))         button2.pack()          canvas = canvas(self, width=400, height=400, bg = 'white')         canvas.pack()      # create x , y axes         canvas.create_line(100,250,400,250, width=2)         canvas.create_line(100,250,100,50,  width=2)  # creates divisions each axle             in range(11):             x = 100 + (i * 30)             canvas.create_line(x,250,x,245, width=2)             canvas.create_text(x,254, text='%d'% (10*i), anchor=n)          in range(6):             y = 250 - (i * 40)             canvas.create_line(100,y,105,y, width=2)             canvas.create_text(96,y, text='%5.1f'% (50.*i), anchor=e)          self.update_graph()      def update_graph(self): # here canvas create line causes trouble                              canvas.create_line(100,250,140,200, width=2)         self.after(100,self.update_graph)   whith code error "canvas not defined".  if add self canvas in update_graph,   self.canvas.create_line(100,250,140,200, width=2) attributeerror: 'pageone' object has no attribute 'canvas' 

what missing here?

canvas defined in scope of constructor (__init__) method. if want able access elsewhere in class, need make instance variable. instead of,

 canvas = canvas(self, width=400, height=400, bg = 'white') 

make it,

 self.canvas = canvas(self, width=400, height=400, bg = 'white') 

now, everywhere else in code reference canvas, change self.canvas. should fix problem.

on unrelated note, problem i'm seeing in update_graph calls recursively, or on , over. perhaps change this:

    def update_graph(self):         # line quite long. maybe shorten it?         self.after(100, lambda: canvas.create_line(100,250,                                                    140,200, width=2)) 

hope helps!

edit: redefinition of update_graph makes sense if want 1 fixed line drawn. if intend add other functionality, such periodic updates, original code correct, bryan pointed out.


Comments