monkey334
monkey334

Reputation: 337

How to draw a line on a canvas?

I've read some tutorials on the internet but I can't seem to find anything that shows me how to draw a line

Can anyone help?

I tried doing

p = Canvas(height = 600, width = 800).place(x=0,y=0)
p.create_rectangle(50, 25, 150, 75, fill="blue")

and, unfortunately, it did not work.

Upvotes: 1

Views: 27098

Answers (2)

Ridwan
Ridwan

Reputation: 1

http://www.python-course.eu/tkinter_canvas.php

Your answer how to draw any line using canvas.

Great source for learning tkinter. I hope it useful for you, like I do

from tkinter import *    
canvas_width = 500
canvas_height = 150

def paint( event ):
   python_green = "#476042"
   x1, y1 = ( event.x - 1 ), ( event.y - 1 )
   x2, y2 = ( event.x + 1 ), ( event.y + 1 )
   w.create_oval( x1, y1, x2, y2, fill = python_green )

master = Tk()
master.title( "Painting using Ovals" )
w = Canvas(master, 
           width=canvas_width, 
           height=canvas_height)
w.pack(expand = YES, fill = BOTH)
w.bind( "<B1-Motion>", paint )

message = Label( master, text = "Press and Drag the mouse to draw" )
message.pack( side = BOTTOM )

mainloop()

I just copied from the site.

Upvotes: 0

tobias_k
tobias_k

Reputation: 82949

Not entirely sure what you are asking, as you are neither showing us your complete code nor stating what exactly "did not work". It seems you already found how to draw a rectangle, and the same tutorial should also have had something about drawing lines, like the one linked in the comments.

Since that seemed not to help you, maybe the problem is that you are using Python 3, where the Tkinter package was renamed to tkinter. This example should work for you:

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

for i in range(10):
    canvas.create_line(50 * i, 0, 50 * i, 400)
    canvas.create_line(0, 50 * i, 400, 50 * i)
canvas.create_rectangle(100, 100, 200, 200, fill="blue")
canvas.create_line(50, 100, 250, 200, fill="red", width=10)

root.mainloop()

Addendum: I just noticed two actual problems with your code:

  • By doing p = Canvas(height = 600, width = 800).place(x=0,y=0), the variable p will not be assigned the Canvas, but the return value of place, i.e. None.
  • Also, the constructor should include the parent element you want to add the Canvas to (root in my example).

Here is a very thorough introduction to all of Tkinter, and particularly the Canvas element.

Upvotes: 7

Related Questions