1

我一直在尝试使用 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)

不过,这条线没有显示在我的画布中,也没有给出错误。有什么帮助吗?

4

2 回答 2

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

您需要为 create_line 提供行的起点和终点处的 x,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作为参考。

于 2013-05-11T09:56:01.233 回答
0

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

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

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

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

于 2013-05-11T14:43:11.017 回答