Using Tkinter in Jupyter Notebook

Tkinter is a Python library used for creating and developing GUI-based applications. It is completely open-source and works on Windows, Mac, Linux, and Ubuntu. Tkinter usually comes pre-installed with Python, but if needed, you can install it using pip install tkinter. In Jupyter Notebook, you can run Tkinter applications, though they will open in separate windows.

Verifying Tkinter Installation

Once you have Tkinter available, you can verify the installation by importing it ?

from tkinter import *
print("Tkinter imported successfully!")
Tkinter imported successfully!

Basic Tkinter Window

Let's create a simple window with a button that displays text when clicked ?

import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Tkinter in Jupyter")
root.geometry("400x200")

def show_message():
    label = tk.Label(root, text="Hello from Tkinter!", font=("Arial", 14))
    label.pack(pady=10)

# Create a button
button = tk.Button(root, text="Click Me", command=show_message, font=("Arial", 12))
button.pack(pady=20)

# Start the GUI event loop
root.mainloop()

Tkinter with Jupyter Notebook Considerations

When using Tkinter in Jupyter Notebook, keep these points in mind:

  • Separate Window: Tkinter creates a separate window outside the notebook
  • Event Loop: mainloop() blocks the notebook cell until the window is closed
  • Interactive Development: You may need to restart the kernel if the window becomes unresponsive

Example with Entry Widget

Here's a more interactive example with an entry field ?

import tkinter as tk

def display_text():
    user_input = entry.get()
    result_label.config(text=f"You entered: {user_input}")

# Create main window
window = tk.Tk()
window.title("Text Input Example")
window.geometry("300x150")

# Create widgets
entry = tk.Entry(window, width=20, font=("Arial", 10))
entry.pack(pady=10)

submit_btn = tk.Button(window, text="Submit", command=display_text)
submit_btn.pack(pady=5)

result_label = tk.Label(window, text="", font=("Arial", 10))
result_label.pack(pady=10)

window.mainloop()

Best Practices

Practice Description Benefit
Use import tkinter as tk Import with alias Cleaner namespace
Set window size Use geometry() Consistent appearance
Handle window closing Use protocol() Clean shutdown

Conclusion

Tkinter works in Jupyter Notebook but opens separate windows outside the notebook interface. Use mainloop() to start the GUI, and be prepared to restart the kernel if needed during development.

Updated on: 2026-03-25T19:37:27+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements