Python Forum
[Tkinter] integrating plot to box
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] integrating plot to box
#1
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 Dodgy
Thanks for helping Heart

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()
________
Reply
#2
https://matplotlib.org/3.1.0/gallery/use...gskip.html
Larz60+ likes this post
Reply
#3
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 ...) Sad
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
Reply
#4
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)
Reply
#5
No worries, integrating matplotlib plots into Tkinter can be tricky Rolleyes
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.
Reply
#6
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 Dance .
I will try your suggestions very soon and keep you informed of my progres
thanks again
mik
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation Integrating py script onto GUI. edwin4project 0 1,270 Oct-28-2020, 02:20 AM
Last Post: edwin4project
  Integrating code with gui.py using modular math Pleiades 0 2,295 May-02-2018, 04:02 PM
Last Post: Pleiades
  [PyQt] integrating Pydesigner and python JackDinn 0 2,327 Mar-01-2018, 02:22 PM
Last Post: JackDinn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020