tkinter is a popular GUI (Graphical User Interface) library in Python that allows you to create visually appealing and interactive applications. In this blog post, we will learn how to display real-time graphs and charts using tkinter.
Installing tkinter
Tkinter is included with Python, so you don’t need to install anything additional. However, make sure you have Python installed on your system.
Setting up the project
To get started, create a new Python file and import the necessary libraries.
import tkinter as tk
import matplotlib.pyplot as plt
import random
Next, create an instance of the tkinter
window and set its size and title.
root = tk.Tk()
root.title("Real-time Graph")
root.geometry("500x500")
Creating a real-time graph
To display real-time data on a graph, we will be using the matplotlib
library. First, let’s create a frame inside the window where we will display the graph.
frame = tk.Frame(root)
frame.pack()
Next, we need to define a function that will be called periodically to update the graph with new data points.
def update_graph():
# Generate random data for demonstration
x = [i for i in range(10)]
y = [random.randint(1, 10) for _ in range(10)]
# Clear the frame before updating the graph
for widget in frame.winfo_children():
widget.destroy()
# Create a matplotlib figure and axis
figure = plt.Figure(figsize=(5, 4), dpi=100)
ax = figure.add_subplot(111)
# Plot the data
ax.plot(x, y)
# Add labels and titles
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Real-time Graph")
# Display the graph in the tkinter frame
canvas = FigureCanvasTkAgg(figure, frame)
canvas.draw()
canvas.get_tk_widget().pack()
# Schedule the next update after 1 second
root.after(1000, update_graph)
# Call the function to start the real-time graph
update_graph()
# Run the tkinter main loop
root.mainloop()
Conclusion
In this blog post, we learned how to display real-time graphs and charts using tkinter and matplotlib in Python. By periodically updating the graph with new data points, we can visualize dynamic data in an interactive and visually appealing way.
Remember to install the necessary libraries, set up the project, and define the update function that retrieves and updates the data for the graph. With tkinter, creating real-time graphs in Python is both easy and powerful. Happy coding!