使用python GUI中的坐标列表创建一行

时间:2013-05-11 07:33:46

标签: python user-interface tkinter line coordinates

我一直在尝试使用create_line和(x,y)点列表创建图形。

import Tkinter
Screen = [a list of screen coordinates]
World = []
for x,y in screen:
    World.append(somefunctiontochange(x,y))
    if len(World) >= 2:
        Canvas.create_line(World)

但是我的画布中没有显示该行,也没有给出错误。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

我花了一些时间,但这就是你以你想要的方式画到画布的方式:

import Tkinter as tk

root = tk.Tk()
root.geometry("500x500")
root.title("Drawing lines to a canvas")

cv = tk.Canvas(root,height="500",width="500",bg="white")
cv.pack()

def linemaker(screen_points):
    """ Function to take list of points and make them into lines
    """
    is_first = True
    # Set up some variables to hold x,y coods
    x0 = y0 = 0
    # Grab each pair of points from the input list
    for (x,y) in screen_points:
        # If its the first point in a set, set x0,y0 to the values
        if is_first:
            x0 = x
            y0 = y
            is_first = False
        else:
            # If its not the fist point yeild previous pair and current pair
            yield x0,y0,x,y
            # Set current x,y to start coords of next line
            x0,y0 = x,y

list_of_screen_coods = [(50,250),(150,100),(250,250),(350,100)]

for (x0,y0,x1,y1) in linemaker(list_of_screen_coods):
    cv.create_line(x0,y0,x1,y1, width=1,fill="red")

root.mainloop()

你需要在行的起点和终点提供带有x,y位置的create_line,在上面的示例代码中(有效)我​​绘制了连接点(50,250),(150,100),(250,250)的四条线),(350,100)曲折线

值得指出的是,画布上的x,y坐标开始于左上角而不是左下角,认为它不像是图中左边的x,y = 0,0画布以及更多如何打印到从左上角开始向x中向右移动的页面,并在向下移动页面时y递增。

我用过: http://www.tutorialspoint.com/python/tk_canvas.htm作为参考。

答案 1 :(得分:0)

如果您没有收到错误并且您确定正在调用您的函数,那么您可能遇到以下三个问题之一:

您的画布是否可见?初学者的一个常见错误就是忘记打包/格栅/放置画布,或忽略对所有容器执行此操作。一种简单的验证方法是暂时为您的画布提供一个非常明亮的背景,以便它从GUI的其余部分中脱颖而出。

您是否设置了滚动区域?另一种解释是绘图正在进行,但它发生在画布可视部分之外的区域。您应该在创建绘图后设置画布的scrollregion属性,以确保您绘制的所有内容都可以显示。

您的画布和画布对象是否具有合适的颜色?您可能已将画布的背景更改为黑色(因为您未在问题中显示该代码),并且在创建线条时,您使用的是默认颜色黑色。