How to update a plot on Tkinter canvas?


Creating interactive and dynamic plots is a crucial aspect of developing graphical user interfaces (GUIs) in Python. Tkinter, a standard GUI toolkit for Python, provides a Canvas widget that facilitates the drawing of various shapes, including plots.

In this article, we will explore the intricacies of updating a plot on a Tkinter canvas dynamically. Understanding this process is essential for building responsive and user-friendly applications with real-time data visualization.

Setting Up the Canvas

Before delving into dynamic updates, let's establish the foundation by creating a simple Tkinter canvas and drawing a static plot. The Canvas widget is the key element that allows us to display and manipulate graphics. Below is a basic example that draws a line plot −

Example

import tkinter as tk

# Create the main Tkinter window
root = tk.Tk()
root.title("Example of Static Plot")
# Set window dimensions
root.geometry("720x250")

# Create a Canvas widget
canvas = tk.Canvas(root, width=400, height=200)
canvas.pack()

# Coordinates for a simple line plot
x1, y1 = 50, 50
x2, y2 = 200, 150

# Create a line on the canvas
line = canvas.create_line(x1, y1, x2, y2, fill="green", width=2)

# Start the Tkinter event loop
root.mainloop()

The above code sets up a Tkinter window with a canvas and draws a static line plot on it. Understanding how to create a static plot is crucial for our next examples.

Output

In this section we will see three different examples of updating the tkinter Canvas plot.

Updating Plot Coordinates

To update a plot dynamically, we need a mechanism to modify its coordinates during runtime. The canvas.coords method allows us to change the coordinates of items on the canvas. Let's extend the previous example to include a button that updates the plot when pressed −

Example

import tkinter as tk

def update_plot():
   # Update the coordinates of the line
   canvas.coords(line, 10, 10, x2, y2)

   # Change the color of the line
   canvas.itemconfig(line, fill="red")

# Create the main Tkinter window
root = tk.Tk()
root.title("Updating Plot Coordinates Example")
# Set window dimensions
root.geometry("720x250")

# Create a Canvas widget
canvas = tk.Canvas(root, width=400, height=200)
canvas.pack()

# Initial coordinates of the line
x1, y1 = 50, 50
x2, y2 = 200, 200

# Create a line on the canvas
line = canvas.create_line(x1, y1, x2, y2, fill="green", width=2)

# Create a button to trigger the update
update_button = tk.Button(root, text="Update Plot", command=update_plot)
update_button.pack()

# Start the Tkinter event loop
root.mainloop()

In this example, the update_plot function is called when the "Update Plot" button is pressed. It utilizes canvas.coords to modify the coordinates of the line, effectively updating the plot. Additionally, canvas.itemconfig is used to change the color of the line.

Output

After clicking the Update Plot button, it will change the plot as follows:

Animating the Plot

To create a more engaging user experience, we can introduce animation to our plot updates. Tkinter provides the after method, allowing us to schedule a function to be called after a specified time. We can leverage this to create a simple animation where the plot gradually moves across the canvas −

Example

import tkinter as tk

def animate_plot():
   global x1, y1, x2, y2

   # Update the coordinates of the line
   canvas.coords(line, x1, y1, x2, y2)

   # Increment the x-coordinates for animation
   x1 += 5
   x2 += 5

   # Schedule the next animation frame
   canvas.after(50, animate_plot)

root = tk.Tk()
root.title("Animated Plot Example")
root.geometry("720x250")

canvas = tk.Canvas(root, width=400, height=200)
canvas.pack()

x1, y1 = 50, 50
x2, y2 = 200, 150

line = canvas.create_line(x1, y1, x2, y2, fill="blue", width=2)
animate_plot()
root.mainloop()

In this example, the animate_plot function is called repeatedly with a delay of 50 milliseconds between each call, creating a smooth animation effect. The x-coordinates of the line are incremented during each frame, causing the plot to move horizontally across the canvas.

Output

Updating Bar Charts

While the previous examples focused on line plots, updating other types of plots, such as bar charts, follows a similar approach. Let's create an example with a bar chart, where clicking a button updates the heights of the bars −

Example

import tkinter as tk
import random

def update_chart():
   # Update the heights of the bars with random values
   for i in range(len(bars)):
      new_height = random.randint(10, 150)
      x1, y1, x2, y2 = canvas.coords(bars[i])
      canvas.coords(bars[i], x1, 200 - new_height, x2, 200)

   # Change the color of the bars
   for bar in bars:
      canvas.itemconfig(bar, fill="green")

# Create the main Tkinter window
root = tk.Tk()
root.title("Bar Chart Update Example")
# Set window dimensions
root.geometry("720x250")

# Create a Canvas widget
canvas = tk.Canvas(root, width=400, height=200)
canvas.pack()

# Initial data for the bar chart
bar_data = [50, 80, 120, 40]

# Create bars on the canvas
bars = []
bar_width = 50
for i, height in enumerate(bar_data):
   x1 = i * (bar_width + 10) + 20
   y1 = 200 - height
   x2 = x1 + bar_width
   y2 = 200
   bar = canvas.create_rectangle(x1, y1, x2, y2, fill="blue")
   bars.append(bar)

# Create a button to trigger the update
update_button = tk.Button(root, text="Update Chart", command=update_chart)
update_button.pack()

# Start the Tkinter event loop
root.mainloop()

In this example, the update_chart function iterates through each bar, updating its height with a random value. The canvas.itemconfig method is then used to change the color of each bar to green.

Output

After clicking the Update Chart button, it will change the chart as follows −

Conclusion

Mastering dynamic plot updates on Tkinter canvas in Python is a valuable skill for building interactive and visually appealing applications. We've explored the fundamental concepts of updating plot coordinates, creating animations, and updating different types of plots, such as line plots and bar charts.

Armed with this knowledge, developers can enhance the user experience by providing real-time data visualization and creating responsive GUIs. As you continue to work with Tkinter and canvas, experimenting with these concepts will open the door to more advanced and sophisticated graphical applications.

Updated on: 06-Dec-2023

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements