1

Beside the lines, I would like to show '1x', '2x', '3x', '4x' and '5x', respectively.

I could not upload the image due to insufficient reputation.

Thanks.

def draw_lines():
    import Tkinter

    L1 = [0, 0, 0, 1]
    L2 = [1, 0, 1, 2]
    L3 = [2, 0, 2, 3]
    L4 = [3, 0, 3, 4]
    L5 = [4, 0, 4, 5]

    top = Tkinter.Tk()
    canvas = Tkinter.Canvas(top, width=500, height=500)

    offset = 1
    scale = 50
    for L in [L1, L2, L3, L4, L5]:
        canvas.create_line(*[scale*(x + offset) for x in L])

    canvas.pack()
    top.mainloop()
user24397
  • 21
  • 4

2 Answers2

0

create a label then use the place() method:

import Tkinter as tk
#or from Tkinter import Canvas, Label, Tk

L1 = [0, 0, 0, 1]
L2 = [1, 0, 1, 2]
L3 = [2, 0, 2, 3]
L4 = [3, 0, 3, 4]
L5 = [4, 0, 4, 5]

top = tk.Tk()
canvas = tk.Canvas(top, width=500, height=500)

offset = 1
scale = 50
count = 1

for L in [L1, L2, L3, L4, L5]:
    canvas.create_line(*[scale*(i + offset) for i in L])
    #create label and place it above line
    lbl = tk.Label(top, text = "%sx"%(count))
    lbl.place(x=scale * count, y=20)
    #add to count manually
    count += 1

canvas.pack()
top.mainloop()

Try it out and tell me if it works

Serial
  • 7,925
  • 13
  • 52
  • 71
  • No, you don't want to import like that. Doing so dumps a whole bunch of names in the global namespace. You could do `import Tkinter as tk` and then reference everything by placing `tk.` in front of it. Or, since this is a small script, you could just do `from Tkinter import Canvas, Label, Tk`. Regardless, you should never do `from module import *` (I don't even know why Python gives you this feature). –  Dec 05 '13 at 02:45
  • @user24397 No problem! good luck with the rest of your project :) – Serial Dec 05 '13 at 03:53
0

I made a few changes to your for-loop to get what I think you want:

import Tkinter

L1 = [0, 0, 0, 1]
L2 = [1, 0, 1, 2]
L3 = [2, 0, 2, 3]
L4 = [3, 0, 3, 4]
L5 = [4, 0, 4, 5]

top = Tkinter.Tk()
canvas = Tkinter.Canvas(top, width=500, height=500)

offset = 1
scale = 50

# Use enumerate to get index,value pairs (start at 1 for the indexes)
for idx, L in enumerate([L1, L2, L3, L4, L5], 1):
    # Move this up here so we can use it in each of the following lines
    coords = [scale*(i + offset) for i in L]
    # Same as before
    canvas.create_line(*coords)
    # You may have to play with the numbers here to get what you like
    canvas.create_text(coords[0]-14, 53, text="{}x".format(idx))

canvas.pack()
top.mainloop()

Example:

enter image description here

Important references:

  1. enumerate

  2. Tkinter.Canvas.create_text

  3. str.format