【问题标题】:Horizontal Lines in Tkinter PythonTkinter Python 中的水平线
【发布时间】:2014-04-01 22:45:23
【问题描述】:

尝试在 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")

谢谢!

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

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

      【讨论】:

        【解决方案3】:

        行:

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

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

        【讨论】:

          【解决方案4】:

          main() 函数不包含displayHorizontal(),这就是没有出现水平线的原因。

          【讨论】:

          • 谁知道main 包括什么?他没有将其包含在他的代码中。他所做的就是证明他从坐标(50, 50) 到坐标(50, 50) 画了一条线,实际上是一个点:)
          猜你喜欢
          • 2011-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-29
          • 2018-02-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多