【问题标题】:Place dimensions on an object在对象上放置尺寸
【发布时间】:2020-06-23 20:17:38
【问题描述】:

我找不到放置对象尺寸的方法,无论是直线、正方形还是圆形; Python中有什么方法可以像Auto Cad一样放置任何对象的尺寸? ,我正在与tkintercanvas 合作;谢谢。

【问题讨论】:

  • 欢迎来到 SO!我建议您查看Question Guidlines,以提高您获得有用答案的机会。用您尝试过的方法、无效的示例代码等更新您的问题。祝您好运!
  • 画布有用于创建文本的文档化方法。你试过用吗?

标签: python-3.x tkinter tkinter-canvas


【解决方案1】:

我不确定这是否能回答您的问题:

要将 tkinter 画布线放置在特定维度中,您应该这样做:

from tkinter import *
class dimensionPlace:
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root)
        self.canvas.create_line(200, 0, 200, 200) # Creates a line from (200, 0) to (200, 200)
        self.canvas.pack()

        self.root.mainloop()


dimensionPlace()

create_line的参数是:x1,y1,x2,y2,其中x1和y1是起点的x和y坐标,x2和y2是终点的x和y坐标。

编辑:查找线长的公式是这样的,假设您有变量 self.linex1、self.linex2、self.liney1、self.liny2 并且您已包含该行“从数学导入 *”:self.linelength = sqrt((self.linex2 - self.linex1) ** 2 + (self.liney2 - self.liney1) ** 2)

【讨论】:

    【解决方案2】:

    tkinter 中没有什么“开箱即用”的东西可以做你想做的事。您必须编写自己的几何操作程序才能在对象上定位所需的尺寸。

    例如:

    通过以下方式完成:

    import math
    import tkinter as tk
    
    
    class Line:
    
        def __init__(self, canvas, start, end, unit='px'):
            self.canvas = canvas
            self.start = start
            self.end = end
            self.unit = unit
            self.draw()
    
        @property
        def mid_offset(self):
            x0, y0 = self.start
            x1, y1 = self.end
            offset = 20
            return (x0 + x1 + offset) / 2, (y0 + y1 - offset) / 2
    
        @property
        def angle(self):
            x0, y0 = self.start
            x1, y1 = self.end
    
            angle = math.atan2(-(y1 - y0), x1 - x0) * 180 / math.pi
            while angle < 0:
                angle += 360
            return angle
            # return 45
    
        def __abs__(self):
            x0, y0 = self.start
            x1, y1 = self.end
            return round(((x0 - x1) ** 2 + (y0 - y1) ** 2) ** .5, 2)
    
        def draw(self):
            self.canvas.create_line(*self.start, *self.end)
            txt = f'{abs(self)} {self.unit}'
            self.canvas.create_text(*self.mid_offset, angle=self.angle, text=txt)
    
    
    if __name__ == '__main__':
    
        root = tk.Tk()
        canvas = tk.Canvas(root, width=400, height=400)
        canvas.pack(expand=True, fill=tk.BOTH)
    
        Line(canvas, (50, 50), (300, 300))
        Line(canvas, (10, 350), (350, 200))
    
        root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2015-08-22
      • 1970-01-01
      • 2016-05-24
      • 2018-06-12
      • 2021-11-01
      • 1970-01-01
      • 2022-01-18
      • 2016-07-12
      • 1970-01-01
      相关资源
      最近更新 更多