[Tkinter] integrating plot to box - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] integrating plot to box (/thread-41952.html) |
integrating plot to box - zapad - Apr-13-2024 Good morning I am meeting a problem in integrating a matplotlib graph into a tkinter gui: The program works ok ,but it only appears in the shell console. I tried to skim the docs on 'plots': there are a lot of sources, but the examples provided are complex and I cannot identify simple principles adapted to my case.. hence my call: This is a script that retrieves a .txt file and reproduces it into histograms representing the frequency of letters... aka Cesar I would like it to be displayed in my 'frame2' in my source below I deactivated the ''plot' part Thanks for helping import tkinter from tkinter import* import tkinter as tk import re, string from PIL import Image, ImageTk from tkinter import filedialog from unidecode import unidecode from tkinter.scrolledtext import ScrolledText import numpy as np import matplotlib.pyplot as plt #-------------------- Main Window #---------------------------------------------------- root = tk.Tk() root.title(" Python Crypto esssai GUI-005") # nom du script((((((( root.geometry('1230x850+80+80') # taille box #------------------------------------- creation------View gui -----------avec scroll BOX1 txt1 = ScrolledText(root, border=3, bg="tan1",) txt1.config(borderwidth=2, relief="raised", height=10 , width=45, font=('Arial',12,'bold',)) txt1.place(x=30,y=90) #------------------------------------------- FRAME2 frame2=Frame(root,bg = "grey25",width=500, height=310,border=3, cursor = "target",highlightbackground='gray60',highlightthicknes=2) frame2.place(x=600,y=80) ##def openFile(): ## tf = filedialog.askopenfilename( ## initialdir="C:/Users/MainFrame/Desktop/", ## title="Ouvrir fichier", ## filetypes=(("Text Files", "*.txt"),)) #### pathh.insert(tk.END, tf) ## tf = open(tf,mode="r", encoding="utf-8") ## file_cont = tf.read() ## komp = len(file_cont) ## txt1.delete("1.0", "end-1c") ## txt1.insert(tk.END, file_cont) ## tf.close() #--------------------- # Portion PLOT text_file = 'fr-txt.txt' #text_file = txt1.get("1.0","end-1c") letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Initialize the dictionary of letter counts: {'A': 0, 'B': 0, ...} lcount = dict([(l, 0) for l in letters]) # Lecture du txt & compteles occurences for l in open(text_file).read(): try: lcount[l.upper()] += 1 except KeyError: # Ignore characters that are not letters pass # The total number of letters norm = sum(lcount.values()) text_file #--------------------- fig = plt.figure() ax = fig.add_subplot(111) # The bar chart, with letters along the horizontal axis and the calculated # letter frequencies as percentages as the bar height x = range(26) ax.bar(x, [lcount[l]/norm * 100 for l in letters], width=0.8, color='g', alpha=0.5, align='center') ax.set_xticks(x) ax.set_xticklabels(letters) ax.tick_params(axis='x', direction='out') ax.set_xlim(-0.5, 25.5) # ------------------------------------Bouton actif btnDec=Button(root,text=" go",bg='violetred', fg='goldenrod1', ) btnDec.config(borderwidth=2, relief="raised", width=12, height=1, font=('Arial',12,'bold',)) btnDec.place(x=840,y=480) # ----------------------------------FINEX ------------ tk.mainloop()________ RE: integrating plot to box - deanhystad - Apr-13-2024 https://matplotlib.org/3.1.0/gallery/user_interfaces/embedding_in_tk_sgskip.html RE: integrating plot to box - zapad - Apr-14-2024 good day I think I have found and read this snippet long before posting. You will think that I am dumb, but I still have no shame that i have no result (for the moment ...) I have studied the script and found the place where the equation should go : "fig.add_subplot(111) etc....." But my pb is more complex ( to me) due to the fact it is an histogram -with much datas to incorporate. I will try again next week - anyway thank you again mik RE: integrating plot to box - deanhystad - Apr-14-2024 You are looking at the example wrong. This is the important part of the example. It displays fig, your plot, in a tkinter window. canvas = FigureCanvasTkAgg(fig, master=root) # Makes a thing that displays a plot. master can be a frame or notebook page, or a window. canvas.draw() # Call this each time you change your plot. canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) # Places canvas widget inside it's parent/master toolbar = NavigationToolbar2Tk(canvas, root) # Only do this part if you want the plot toolbar. toolbar.update() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)The figure can be anything you want, even one that starts like this: fig = plt.figure() ax = fig.add_subplot(111) RE: integrating plot to box - SandraYokum - Apr-15-2024 No worries, integrating matplotlib plots into Tkinter can be tricky First, you need to make sure you have the FigureCanvasTkAgg and optionally NavigationToolbar2Tk imported from matplotlib.backends.backend_tkagg. These allow you to embed matplotlib figures into your Tkinter interface. # Assuming your fig and ax are already set up as you described: canvas = FigureCanvasTkAgg(fig, master=frame2) # Setting master to frame2 to display it there canvas.draw() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) # Packing it into the GUI # If you want the navigation toolbar: toolbar = NavigationToolbar2Tk(canvas, frame2) toolbar.update() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)Just paste this right after where you set up your fig and ax. This code places your plot within frame2 and fits it into the space you've specified. If you've already packed frame2 into your main window, everything should display as expected. Give it a go and tweak the packing options if you need to adjust the layout. RE: integrating plot to box - zapad - Apr-20-2024 hello I apologize for my late reply ... I have been outside the country for 5 days and am now back home with my PC. I am very surprised by your kindness & the quality or your advices . I will try your suggestions very soon and keep you informed of my progres thanks again mik |