如何在画布上绘制一条线?

1 投票
2 回答
25773 浏览
提问于 2025-04-20 04:21

我在网上看了一些教程,但就是找不到教我怎么画一条线的内容。

有没有人能帮帮我?

我试着这样做了:

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

但是,很不幸,这并没有成功。

2 个回答

0

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

我只是从网站上复制的。

7

我不太确定你在问什么,因为你没有给我们完整的代码,也没有说明具体“哪里不工作”。看起来你已经找到了如何画矩形的方法,而那个教程里应该也有关于画线的内容,就像评论里提到的这个链接

既然那个没有帮助你,可能问题出在你使用的是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)。

这里有一个非常详细的Tkinter介绍,特别是关于Canvas元素的部分。

撰写回答