Search code examples
pythonpython-3.xtkinterintattributeerror

builtins.AttributeError: 'int' object has no attribute 'create_line'


I have this graphing code that will be used to graph different points onto it. However, when i am setting up my number line for the x-axis, I keep getting an int error.

from tkinter import *

def checkered(canvas, line_distance):
   for x in range(line_distance,canvas_width,line_distance):
      canvas.create_line(x, 0, x, canvas_height, fill="#476042")
   for y in range(line_distance,canvas_height,line_distance):
      canvas.create_line(0, y, canvas_width, y, fill="#476042")
###############################################################################
root = Tk()
canvas_width = 1000
canvas_height = 760
w = Canvas(root, 
           width=canvas_width,
           height=canvas_height)
checkered(w,20)           
w.pack()

a = int(canvas_height / 2)
w.create_line(0, a, canvas_width, a, 
               fill="black",width=3)
b = int(canvas_width / 2)
w.create_line(b, 0, b,canvas_height, 
              fill = "red",width=3)
w.create_text(5, ((canvas_height/2)-10)
              ,text="x",font=12)
w.create_text(b+10 ,5
              ,text='y',font=12)
w.create_text(b+10,a-10
              ,text='0',font=12)
w.create_oval(b-5,a-5,b+5,a+5 
              ,fill = 'black')
w=int(canvas_width/50)
z=int(canvas_width/100)
aa=b+w
bb=a-z
cc=a+z 
w.create_line(aa,bb,aa,cc,
              fill='black',width=3)

mainloop()

Whenever i run the program, i keep getting this message:

line 37, in <module>
builtins.AttributeError: 'int' object has no attribute 'create_line'

This doesn't make sense for me because 'int' worked in line 19 and 22:

a = int(canvas_height / 2)
w.create_line(0, a, canvas_width, a, 
               fill="black",width=3)

b = int(canvas_width / 2)
w.create_line(b, 0, b,canvas_height, 
              fill = "red",width=3)

Those lines worked fine, it is just this last line that isn't working. Any help would be appreciated.


Solution

  • You set w to an integer:

    w=int(canvas_width/50)
    z=int(canvas_width/100)
    aa=b+w
    bb=a-z
    cc=a+z 
    

    then on the next line still expect it to be a Canvas:

    w.create_line(aa,bb,aa,cc,
                  fill='black',width=3)
    

    Use better variable names; use canvas rather than w for example and you won't be so easily tricked in reusing the name.