使用canvas.create_line设置不同的线宽?

4 投票
2 回答
21943 浏览
提问于 2025-04-15 22:30

有没有人知道为什么我在下面这个例子中,画布上的线宽会不一样呢?

from Tkinter import *
bigBoxSize = 150

class cFrame(Frame):
    def __init__(self, master, cwidth=450, cheight=450):
        Frame.__init__(self, master, relief=RAISED, height=550, width=600, bg = "grey")
        self.canvasWidth = cwidth
        self.canvasHeight = cheight
        self.canvas = Canvas(self, bg="white", width=cwidth, height=cheight, border =0)
        self.drawGridLines()
        self.canvas.pack(side=TOP, pady=20, padx=20)

    def drawGridLines(self, linewidth = 10):
        self.canvas.create_line(0, 0, self.canvasWidth, 0, width= linewidth )
        self.canvas.create_line(0, 0, 0, self.canvasHeight, width= linewidth )

        self.canvas.create_line(0, self.canvasHeight, self.canvasWidth + 2, self.canvasHeight, width= linewidth )
        self.canvas.create_line(self.canvasWidth, self.canvasHeight, self.canvasWidth, 1, width= linewidth )

        self.canvas.create_line(0, bigBoxSize, self.canvasWidth, bigBoxSize, width= linewidth )
        self.canvas.create_line(0, bigBoxSize * 2, self.canvasWidth, bigBoxSize * 2, width= linewidth)


root = Tk()
C = cFrame(root)
C.pack()
root.mainloop()

这让我真的很沮丧,因为我完全不知道发生了什么。如果有人能帮我一下,那就太好了。谢谢!

2 个回答

0

经过一些实验,我觉得我明白发生了什么了——左边的某些线条被画到了画布外面,我觉得这真是太糟糕了。有没有办法让线条的最外边部分都在画布上呢?或者,有没有更简单的方法可以在一个小部件周围或者在画布上画个边框?

0

当你画一条宽度大于1的线时,多出来的像素需要放在某个地方。正如你在后续的帖子中观察到的,有些像素被画到了屏幕外。你需要做的就是调整你最开始的坐标,考虑到线的宽度。

撰写回答