Home > Back-end >  (Python) Use Tkinter to show a plot in an independent window (Jupyter notebook)
(Python) Use Tkinter to show a plot in an independent window (Jupyter notebook)

Time:12-18

I referred to the following useful tutorial video:

enter image description here

CodePudding user response:

Here is a solution that does what you want. Jupyter-notebooks don't use the tk backend for plotting by default so you have to explicitly instruct matplotlib to use it.

That can either be done as shown below, or using the notebook magic %matplotlib as metioned by @acw1668 in the comments.

I personally find that not practical, and there are other solution to use interactive plots inside a notebook, as e.g. jupyter-lab widgets that I would rather refer you to.

from tkinter import *
from PIL import ImageTk, Image
import numpy as np

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')

root = Tk()
root.title("dsafsdff")
root.geometry("400x200")

def graph():
    f, a = plt.subplots(1, 1)
    house_prices = np.random.normal(0., 1, 1000)
    a.hist(house_prices)
    plt.show()

my_button = Button(root, text="afdgfsdgf", command=graph)
my_button.pack()
root.mainloop()   
  • Related