Tkinter Python 中的水平线

4

我想在Tkinter中绘制一个8 x 8的网格,垂直线条已经画好了,但是我似乎无法正确地画出水平线。

这是我的代码:

from tkinter import *

class CanvasGrid:
def __init__(self):
    self.window = Tk()
    self.window.title("Grid")
    self.canvas = Canvas(self.window, width=128, height=128, bg="white")
    self.canvas.pack()

def displayVertical(self):
    self.canvas.create_line(16, 0, 16, 128, fill="red", tags="line")
    self.canvas.create_line(32, 0, 32, 128, fill="red", tags="line")
    self.canvas.create_line(48, 0, 48, 128, fill="red", tags="line")
    self.canvas.create_line(64, 0, 64, 128, fill="red", tags="line")
    self.canvas.create_line(80, 0, 80, 128, fill="red", tags="line")
    self.canvas.create_line(96, 0, 96, 128, fill="red", tags="line")
    self.canvas.create_line(112, 0, 112, 128, fill="red", tags="line")


def displayHorizontal(self):
    self.canvas.create_line(50, 50, 50, 50, fill="blue", tags="line")

谢谢!
4个回答

3
"50 50 50 50" 是一个点而不是一条线,所以你看不到它。"
canvas.create_line(startx, starty, endx, endy __then other args__)

尝试
canvas.create_line(0,50,widthofwindow,50

2

由于方向相同,您可以将起始值传递给一个函数,该函数创建需要的一个或两个方向。

class CanvasGrid:
    def __init__(self):
        self.window = Tk()
        self.window.title("Grid")
        self.canvas = Canvas(self.window, width=128,
                            height=128, bg = "white")
        self.display_lines(16, 0, 16, 128, "red")
        self.display_lines(0, 16, 128, 16, "blue")
        self.canvas.pack()

        self.window.mainloop()

    def display_lines(self, x1, y1, x2, y2, color):
        x_plus = x1     ## all lines are evenly spaced
        y_plus = y1
        for ctr in range(7):
            self.canvas.create_line(x1, y1, x2, y2, fill = color)
            x1 += x_plus
            x2 += x_plus
            y1 += y_plus
            y2 += y_plus

CG = CanvasGrid()

0

这行代码:

def displayHorizontal(self):
    self.canvas.create_line(50, 50, 50, 50, fill = "blue",
                            tags = "line")

没有长度,它在x和y坐标上都从50开始并结束。为什么不试试0,50,128,50


-1

main()函数没有包含displayHorizontal(),这就是为什么水平线没有显示出来的原因。


1
谁知道 main 包含了什么?他没有在他的代码中包含那个。他所包含的是证明他从坐标 (50, 50) 到坐标 (50, 50) 画了一条直线,实际上就是一个点 :) - Adam Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接