2 Replies - 287 Views - Last Post: 23 October 2013 - 04:27 AM Rate Topic: -----

#1 codeblox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-October 13

Note sure why I'm getting an AttributeError

Posted 22 October 2013 - 07:09 PM

I am scratching my head here... What I am expecting is that when I click the button, the canvas deletes itself. Instead, it's complaining that 'w' does not exist in my remove_w method.


from tkinter import *

class CreateCanvas:
	def __init__(self, root):
		
		frame1 = Frame(root) 
		frame1.pack()
		
		w = Canvas(frame1, width = 200, height = 100)
		w.pack()
		
		frame2 = Frame(root)
		frame2.pack()
		
		button = Button(frame2, text = "Del", command = self.remove_w)
		button.pack()
		
		
		w.create_line(0, 0, 200, 100)
		w.create_line(0, 100, 200, 0, fill = "red", dash = (4, 4))
		
		w.create_rectangle(50, 25, 150, 75, fill = "blue")
		
	def remove_w(self):
		self.w.delete(ALL)
		

		
		

tk = Tk()

app = CreateCanvas(tk)

tk.mainloop()





Is This A Good Question/Topic? 0
  • +

Replies To: Note sure why I'm getting an AttributeError

#2 codeblox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-October 13

Re: Note sure why I'm getting an AttributeError

Posted 22 October 2013 - 07:29 PM

Hmm... It seems to work if I prefix these references with "self" (this). I don't understand why I should need to do this in this case. I have other variables that I didn't need to do this for.
Was This Post Helpful? 0
  • +
  • -

#3 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2133
  • View blog
  • Posts: 3,269
  • Joined: 21-June 11

Re: Note sure why I'm getting an AttributeError

Posted 23 October 2013 - 04:27 AM

If you do w = Canvas(...) you're creating a local variable that lives only during the call to __init__ and can not be accessed as self.w. If you do self.w = Canvas(...) you create an instance variable that can be accessed from any method or function that has access to the object.

Quote

I have other variables that I didn't need to do this for.


Whenever you set a variable that you want to access as a member of the object, you do need to write foo.bar = baz.

This post has been edited by andrewsw: 23 October 2013 - 05:04 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1