尝试在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")
谢谢!
答案 0 :(得分:1)
由于它与任一方向的代码相同,因此您可以将起始值传递给创建任意/两个方向的函数(如果需要)。
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()
答案 1 :(得分:0)
该行:
def displayHorizontal(self):
self.canvas.create_line(50, 50, 50, 50, fill = "blue",
tags = "line")
没有长度,它在x和y坐标中以50开始和结束。为什么不试试0,50,128,50
。
答案 2 :(得分:0)
50 50 50 50
是一个点而不是一条线,这就是为什么你没有看到它。
信息:
canvas.create_line(startx, starty, endx, endy __then other args__)
尝试
canvas.create_line(0,50,widthofwindow,50
答案 3 :(得分:-1)
main()
功能不包括displayHorizontal()
,这就是水平线没有出现的原因。