请问tkinter canvas create_line()关于画虚线时dash参数的详解与原理
问题描述#
在使用 tkinter canvas 的 create_line () 画虚线时,对于 dash 参数不是很理解,不太清楚是什么样的机制。
百度包括书上提的都是说 dash 元组的第一个数字 是实线,第二个数字是空白,如此循环直到所有元组数字用完又重新开始。例如 dash=(5,3) 是产生 5 像素实线,3 像素空白。
实践时,我一直在根据这些解释去想它是怎样去划线的,可是怎么想都没想通,可否根据后面的示例帮忙解答下?谢谢
示例代码#
from tkinter import *
def get_screen_size(root):
"""获取屏幕宽高"""
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
return screen_width, screen_height
def get_center_location(root, width, height):
"""获取屏幕居中位置"""
screen_width, screen_height = get_screen_size(root)
return (screen_width - width) / 2, (screen_height - height) / 2
width = 800
height = 600
bg_color = '#39889f'
min_width = 400
min_height = 200
# 新建窗口
root = Tk()
root.title('such_test') # 窗口标题
x, y = get_center_location(root, width, height)
root.geometry('%dx%d+%d+%d' % (width, height, x, y)) # 窗口宽高、位置
root.configure(bg=bg_color) # 窗口背景色
root.maxsize(*get_screen_size(root)) # 设置窗口拖拽时的最大大小
root.minsize(min_width, min_height) # 设置窗口拖拽时的最小大小
# root.overrideredirect(True) # 去掉边框
root.config(cursor='heart')
# 画布
canvas = Canvas(root, width=width, height=height)
canvas.create_rectangle(0, 0, width, height, outline=None, fill=bg_color)
canvas.create_rectangle(0, 0, width, height, outline=None, activefill='skyblue', activestipple="gray50")
canvas.pack()
# 虚线
canvas.create_line(60, 100, 60, 200, dash=(3, 1))
canvas.create_line(70, 100, 70, 200, dash=(5, 1))
canvas.create_line(80, 100, 80, 200, dash=(3, 1, 1))
canvas.create_line(90, 100, 90, 200, dash=(3, 1, 1, 1))
canvas.create_line(100, 100, 100, 200, dash=(5, 2, 2, 2))
canvas.create_line(110, 100, 110, 200, dash=(5, 2, 2, 2, 2, 2))
root.mainloop()
推荐文章: