def main():
# 建立带权图
G = nx.Graph()
# 向图中添加边,每条边都有一个权值
G.add_edge('A', 'B', weight=5)
G.add_edge('A', 'C', weight=3)
G.add_edge('A', 'D', weight=2)
G.add_edge('B', 'C', weight=1)
G.add_edge('B', 'D', weight=2)
G.add_edge('C', 'D', weight=4)
source=nameEntry5.get()
target=nameEntry6.get()
return nx.dijkstra_path(G, source, target) # 顶点 0 到 顶点 3 的最短加权路径
# 两个指定顶点之间的最短加权路径的长度
return nx.dijkstra_path_length(G, source, target) # 最短加权路径长度
如何得到一个点遍历所有点到另一点的最短路径,又怎么在tkinter的用户界面里显示该无向图并在图上标注这条路径呢
可以在用户界面中添加一个按钮,使得在用户点击按钮时调用函数main。在函数中,可以使用 NetworkX 中的 Dijkstra 算法来计算两点之间的最短路径。
下面是一个例子,展示了如何在带权无向图中查找两个指定顶点之间的最短加权路径:
import networkx as nx
def main():
# 建立带权图
G = nx.Graph()
# 向图中添加边,每条边都有一个权值
G.add_edge('A', 'B', weight=5)
G.add_edge('A', 'C', weight=3)
G.add_edge('A', 'D', weight=2)
G.add_edge('B', 'C', weight=1)
G.add_edge('B', 'D', weight=2)
G.add_edge('C', 'D', weight=4)
source = nameEntry5.get()
target = nameEntry6.get()
# 两个指定顶点之间的最短加权路径
shortest_path = nx.dijkstra_path(G, source, target)
print(shortest_path) # 顶点 A 到 顶点 D 的最短加权路径
# 两个指定顶点之间的最短加权路径的长度
shortest_path_length = nx.dijkstra_path_length(G, source, target)
print(shortest_path_length) # 最短加权路径长度
要在 Tkinter 的用户界面中显示图并在图上标注路径,可以使用绘图工具如 Matplotlib 或者 Pyplot。可以在绘制图之后使用 annotate 函数来在图上标注路径。
仅供参考,望采纳,谢谢。
望采纳!!!点击回答右侧采纳即可!!
对于你的第一个问题
你可以使用 NetworkX 中的最短路径算法,如 Dijkstra 算法来计算图中两个指定顶点之间的最短路径。
例如,假设你已经使用 NetworkX 建立了一个带权的无向图 G,并且已经输入了起点和终点的名称(分别为 source 和 target)。那么,你可以使用以下代码来计算两个指定顶点之间的最短路径:
# 两个指定顶点之间的最短加权路径
path = nx.dijkstra_path(G, source, target)
# 两个指定顶点之间的最短加权路径的长度
length = nx.dijkstra_path_length(G, source, target)
计算完最短路径后,你可以使用 Matplotlib 库在 Tkinter 的用户界面中绘制图像,并在图上标注这条路径。
下面是绘制图像
import matplotlib.pyplot as plt
# 在 Tkinter 的用户界面中绘制图像
plt.plot([x[0] for x in path], [x[1] for x in path])
plt.show()
如果你想在图上标注最短路径,可以使用以下代码:
import matplotlib.pyplot as plt
# 绘制图像
plt.plot([x[0] for x in path], [x[1] for x in path])
# 在图上标注最短路径
plt.annotate("path", xy=path[0], xytext=path[-1], arrowprops=dict(facecolor='red', shrink=0.1))
plt.show()
我想实现的最短路径是两点间遍历图上所有点后的最短路径