2013-05-11 74 views
1

我一直在尝试使用create_line和(x,y)点列表创建图。使用Python中的坐标列表创建一条线GUI

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) 

该行虽然没有显示在我的画布上,也没有给出错误。任何帮助?

+0

你应该提到你正在使用Tkinter(我认为?) – 2013-05-11 07:36:46

+0

是的,我拥有所有这些。这只是我整体代码的一部分。我编辑它。 – user2372332 2013-05-11 07:46:56

+0

要使代码在本网站上正常显示,您需要[缩进4个空格](http://meta.stackexchange.com/a/22189/221039)。 – 2013-05-11 07:51:06

回答

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供应create_line,在该行的起点和终点y位置,在上面的示例代码(工程)中,我绘制了连接点(50,250),(150,100),(250,250),(350,100)的四条线,其曲线如下:

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

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

+0

感谢您的回复。但是我想的是一系列通过点相互连接的线条。就像一个图。 – user2372332 2013-05-11 10:48:20

+0

我已编辑我的回复匹配 – Noelkd 2013-05-11 11:09:27

+0

哦,太棒了:)非常感谢! – user2372332 2013-05-11 12:42:15

0

如果你没有得到错误,你肯定你的函数被调用,你可能有三个问题之一:

是你的画布可见?对于初学者来说,一个常见的错误是要么忘记打包/网格/放置画布,要么忽略为所有容器做这件事。一种简单的验证方法是暂时给画布一个非常明亮的背景,以便从GUI的其余部分突出显示。

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

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

+0

好的。生病去检查。谢谢 :) – user2372332 2013-05-12 01:29:57