1

I have a problem using matplotlib in Tkinter.

Here is the plan:
1. Define a Button and a Frame (Frame_0) using Tkinter.
2. By clicking the Button to plot the sin-function using matplotlib, which is shown in Frame_0
.

But I don't know how to do it.

I am just a beginner. But I just think the easist way to do it might be, 'selecting' the widget by using get_tk_widget(), is it possible? Or is there some other commands to do it?

Hope you understand my poor English and my beginners question. Here is the code. Thank you all.

# -*- coding: utf-8 -*-

from Tkinter import *

import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure


def command_0():
    f = Figure(figsize=(5, 3), dpi=100)
    a = f.add_subplot(111)
    t = arange(0.0, 3.0, 0.01)
    s = sin(2 * pi * t)
    a.plot(t, s)

    dataPlot = FigureCanvasTkAgg(f, master=root)
    dataPlot.show()
    dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
    root.mainloop()


def Main():
    global root

    root = Tk()
    root.title("Program")
    root['background']='gray'

    w = root.winfo_screenwidth()
    h = root.winfo_screenheight()
    root.geometry("%dx%d" %(w, h))
    root.state("zoomed")

    global Frame_0
    Frame_0 = Frame(root)
    Frame_0.place(height=600, width=800, x=10, y=10)


    Frame_1 = Frame(root)
    Frame_1.place(width=120, height=80, x=1000, y=20)
    Button_1 = Button(Frame_1, text = "Click", width = 120, height=80, bg='green', command = command_0)
    Button_1.place(x=1000, y=20)
    Button_1.grid(row=0, column=0)
    Button_1.pack()


    root.mainloop()
    return
Main()

1 Answer 1

2

If you wont to show it in frame_0, i don't know why you are setting the master=root. Simply change:

dataPlot = FigureCanvasTkAgg(f, master=root)

to:

dataPlot = FigureCanvasTkAgg(f, master=Frame_0)

Also you don't need that root.mainloop() at the end of the function.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.