0

Need help with matplotlib in tkinter, can't seem to get the entry to then show of the correct graph. I would like to type in 'x**2' and show the graph for this function but it doesn't seem to work. If anyone could help me out, I would appreciate it. Thanks in advance.

import tkinter as tk
from tkinter import * 
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import numpy as np
import matplotlib
from matplotlib.figure import Figure
matplotlib.use('TkAgg')

screen = tk.Tk()


screen.title('Function Graph')
screen.geometry('350x200')
function = Entry(screen, width = 20)
function.place(x=123, y=92)
f_label = Label(screen, text='Plot Function: ')
f_label.place(x=145, y= 70)

def plot_g():

    x = np.linspace(-3,3,100)

    y = function.get()

    new_w = tk.Toplevel(screen)


    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.spines['left'].set_position('center') 
    ax.spines['bottom'].set_position('zero') 
    ax.spines['right'].set_color('none') 
    ax.spines['top'].set_color('none') 
    ax.xaxis.set_ticks_position('bottom') 
    ax.yaxis.set_ticks_position('left')
    plt.grid()
    plt.plot(x,y)
    canvas = FigureCanvasTkAgg(fig, master=new_w)
    canvas.draw()
    canvas.get_tk_widget().pack(side = 'bottom', fill= BOTH, expand=True)
    toolbar = NavigationToolbar2Tk(canvas, new_w)
    toolbar.update()



f_button = Button(screen, text= 'Enter', command = plot_g)
f_button.place(x=160, y=120)


screen.mainloop()

lnasal
  • 9
  • 1
  • 7
  • `Entry.get()` returns a string. From the looks of it you want to input a function instead of numbers - you have to find some way to parse the input. See [this](https://stackoverflow.com/questions/594266/equation-parsing-in-python) post for a sample. – Henry Yik Feb 21 '20 at 07:28
  • The simple way is `y = eval(function.get())`. But you should understand the risk of using `eval()`. – acw1668 Feb 21 '20 at 09:20
  • @acw1668 Thank you that worked. May I asked what the risk is with eval() ? – lnasal Feb 21 '20 at 11:32
  • User can input destructive expression. You can seach such information in internet. – acw1668 Feb 21 '20 at 11:35
  • Oh ok thank you, this program was only meant for me anyway, thanks for the heads up. You really helped ! – lnasal Feb 21 '20 at 11:40

0 Answers0