【问题标题】:How to draw a line on a canvas?如何在画布上画线?
【发布时间】:2014-09-06 14:40:00
【问题描述】:

我已经阅读了互联网上的一些教程,但我似乎找不到任何教我如何画线的东西

谁能帮忙?

我试过了

p = Canvas(height = 600, width = 800).place(x=0,y=0)
p.create_rectangle(50, 25, 150, 75, fill="blue")

不幸的是,它不起作用。

【问题讨论】:

    标签: python python-3.x tkinter python-3.3


    【解决方案1】:

    不完全确定您要问什么,因为您既没有向我们展示您的完整代码,也没有说明究竟是什么“不起作用”。看来你已经学会了如何画一个矩形,同样的教程应该也有一些关于画线的东西,比如the one linked in the comments

    由于这似乎对您没有帮助,因此问题可能在于您使用的是 Python 3,其中 Tkinter 包已重命名为 tkinter。这个例子应该适合你:

    import tkinter
    
    root = tkinter.Tk()
    canvas = tkinter.Canvas(root)
    canvas.pack()
    
    for i in range(10):
        canvas.create_line(50 * i, 0, 50 * i, 400)
        canvas.create_line(0, 50 * i, 400, 50 * i)
    canvas.create_rectangle(100, 100, 200, 200, fill="blue")
    canvas.create_line(50, 100, 250, 200, fill="red", width=10)
    
    root.mainloop()
    

    附录: 我刚刚注意到您的代码存在两个实际问题:

    • 通过执行p = Canvas(height = 600, width = 800).place(x=0,y=0),变量p不会被分配Canvas,而是place的返回值,即None
    • 此外,构造函数应包含您想要将Canvas 添加到的父元素(在我的示例中为root)。

    这是一个very thorough introduction to all of Tkinter,尤其是 Canvas 元素。

    【讨论】:

    • 嗨。感谢你的回答。弹出此错误但是 AttributeError: 'NoneType' object has no attribute 'create_rectangle' 这与我使用我在主帖中所说的代码行时发生的错误相同。
    • 抱歉。我收回我之前的声明。它确实有效,并且我在使用该代码时使用了我的笔记本电脑,该代码具有错误的 Python 版本,因此它不起作用。它适用于我的主计算机。谢谢。
    • 对不起,另一个问题。看到canvas.create_line部分代码的参数,是什么意思?
    • @monkey334 我刚刚注意到您的代码中的实际问题是什么。请参阅我的编辑。这样的事情不容易发现,这就是为什么您应该始终包含错误消息,以便您可以更快地获得更好的帮助。无论如何,很高兴听到它对你有用。
    【解决方案2】:

    http://www.python-course.eu/tkinter_canvas.php

    你的答案如何使用画布绘制任何线条。

    学习 tkinter 的绝佳资源。 我希望它对你有用,就像我一样

    from tkinter import *    
    canvas_width = 500
    canvas_height = 150
    
    def paint( event ):
       python_green = "#476042"
       x1, y1 = ( event.x - 1 ), ( event.y - 1 )
       x2, y2 = ( event.x + 1 ), ( event.y + 1 )
       w.create_oval( x1, y1, x2, y2, fill = python_green )
    
    master = Tk()
    master.title( "Painting using Ovals" )
    w = Canvas(master, 
               width=canvas_width, 
               height=canvas_height)
    w.pack(expand = YES, fill = BOTH)
    w.bind( "<B1-Motion>", paint )
    
    message = Label( master, text = "Press and Drag the mouse to draw" )
    message.pack( side = BOTTOM )
    
    mainloop()
    

    我只是从网站上复制的。

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2017-04-02
      相关资源
      最近更新 更多