贴标线(Tkinter)

时间:2013-12-05 02:06:43

标签: python tkinter label

除了这些台词,我还想分别展示'1x','2x','3x','4x'和'5x'。

由于声誉不足,我无法上传图片。

感谢。

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()

2 个答案:

答案 0 :(得分:0)

创建标签,然后使用place()方法:

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()

尝试一下,告诉我它是否有效

答案 1 :(得分:0)

我对你的for循环进行了一些修改,以获得我想要的东西:

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()

示例:

enter image description here

重要参考资料:

  1. enumerate

  2. Tkinter.Canvas.create_text

  3. str.format