首页 > 解决方案 > Python Tkinter:如何在列表/元组中使用多个点创建_line?

问题描述

有一个坐标列表,我想在 Tkinter 画布上画线:

points = [(1,1), (2, 2), (3, 3), (2, 0)]   # etc. This is could have 100 points or more

下一步将调用函数 create_line,但它不支持列表:

Canvas.create_line(1, 1, 2, 2, 3, 3)       #this works ok
Canvas.create_line(points)                 #this doesn't work

那么有没有一种有效的方法来分离列表中的元素并按此顺序将它们插入到函数中?如果可能的话,我希望避免使用 for 循环。

标签: pythonlisttkintertkinter-canvas

解决方案


You can flatten the list points with a list comprehension:

flattened = [a for x in points for a in x]

And turn the elements of that flattened list into arguments with the "*" syntax:

Canvas.create_line(*flattened)

I politely suggest that you overcome your hangup about for loops. It is pretty much impossible to write useful programs without them.


推荐阅读