I have this import tkinter as tk from tkinter import ttk import networkx as nx import…
- User
I have this import tkinter as tk from tkinter import ttk import networkx as nx import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import json
def load_network(file_path): # Load network from JSON file with open(file_path, 'r') as file: data = json.load(file) G = nx.Graph() # Add nodes G.add_nodes_from(data["nodes"]) # Add edges with attributes for path in data["paths"]: G.add_edge(path["path"][0], path["path"][1], distance=path["distance"], trafficCondition=path["trafficCondition"], deliveryUrgency=path["deliveryUrgency"]) return G
def draw_graph(filePath): plt.clf() G = load_network(filePath) pos = nx.spring_layout(G) fig, ax = plt.subplots() nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=1200, edge_color='k', linewidths=0.5, font_size=15, ax=ax) canvas.draw()
def on_dropdown1_select(event): filepathnum=dropdown1.current()+1 draw_graph("output" + str(filepathnum) +".json")
Create main window
root = tk.Tk() root.title("Graph Visualization")
Create graph drawing area
figure = plt.figure(figsize=(6, 4)) ax = figure.add_subplot(111) canvas = FigureCanvasTkAgg(figure, master=root) canvas_widget = canvas.get_tk_widget() canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
Create menu widgets
frame_menu = tk.Frame(root) frame_menu.pack(side=tk.TOP, pady=10)
Dropdown 1
options1 = ["Output 1", "Output 2", "Output 3", "Output 4", "Output 5"] file_path_var = ["output1.json", "output2.json", "output3.json", "output4.json", "output5.json"] dropdown1 = ttk.Combobox(frame_menu, values=options1, textvariable=file_path_var) dropdown1.set(options1[0]) dropdown1.bind("<>", on_dropdown1_select) dropdown1.grid(row=0, column=0, padx=5)
Draw initial graph
draw_graph("output1.json")
Start GUI event loop
root.mainloop()
How can I clear what was previously drawn by networkx before I draw something else
- Assistant
To clear the previous drawing made by Networkx on a Matplotlib FigureCanvasTkAgg in a tkinter application before drawing a new graph, you need to focus on clearing the axis () or the figure () in your drawing function. Since you're calling at the start of , it should clear the current figure. However, managing the subplot explicitly can give you more control, especially in a GUI application where updates are frequent.