- Integrating a Plot to a Tkinter User Interface
- Introduction
- What is Tkinter in Matplotlib?
- How to Create the Tkinter Application?
- Integrating a Plot to a Tkinter User Interface
- Code Examples
- Conclusion
- Рисование графиков. Python. Tkinter
- Using Tkinter and Matplotlib
- Tkinter Graph
- Create Matplotlib Graph With Tkinter in Python
Integrating a Plot to a Tkinter User Interface
According to the TIOBE Programming Community , Python is currently one of the top 3 programming languages in the world. It is a general-purpose and high-level programming language, used for creating websites, Machine Learning Models, Full-Stack applications, and GUI applications.
One of the main features that make Python appealing to developers is its ability to merge and integrate with different hardware and software applications in our computers. In this article, we will learn the basics of Tkinter, its applications, and some ways to integrate a plot into a Tkinter User Interface.
Introduction
As discussed earlier in this article, Python is home to a lot of advanced libraries like NumPy, and Matplotlib that makes our lives easy as developers. Building workable prototypes of applications is possible using Python because Python has a lot of libraries that support GUIs (Graphical User Interfaces) .
There are a lot of libraries in Python that we can use to create attractive GUIs, like Pyglet , wxWidgets , GTK , and Tkinter . Amongst these options, Tkinter is the module of choice for developers to create scalable and visually appealing GUIs.
In this tutorial, we will learn about the Tkinter module, and integrate a plot with it using Matplotlib.
What is Tkinter in Matplotlib?
Open-source, cross-platform Tkinter is a tool that requires little to no coding to produce a useful desktop application, is portable, and is simple to learn. Since Tk and Tkinter are there on most of the UNIX and Windows systems, Tkinter makes GUI application and program development the quickest and simplest.
Here’s what a simple Tkinter GUI application looks like:
How to Create the Tkinter Application?
There are 4 steps to creating a responsive and visually-appealing GUI using Tkinter in Python:
- Importing Tkinter libraries and modules.
- Generating the main window for our GUI app.
- Adding some widgets to our main window according to our needs and requirements.
- Enter and start the Main Event Loop using mainloop() function.
Using these 4 steps, we will create a Weight Convertor using Tkinter in Python.
Integrating a Plot to a Tkinter User Interface
One of the lesser-known features of Matplotlib is its ability to generate GUIs. It offers simple widgets to create partially interactive figures. The widgets created by Matplotlib are not scalable and flexible, hence we will use Tkinter.
Tkinter allows you to create some widgets and give them a windows layout. Matplotlib can be used efficiently to integrate plots and various layouts into a graphical user interface made by Tkinter.
We will start by importing all the Tkinter essentials and creating a function for the SuperShape design. To integrate the SuperShape with the plot, we would use Matplotlib.
Code Examples
- Creating a Tkinter application for displaying plots in Matplotlib In this example, we will embed a plot in the Tkinter application using the concepts we learned in this article.
Output
Conclusion
- In this article, we learned about Tkinter; an open-source, cross-platform utility, that can be used to create useful desktop applications with little to no coding.
- We learned that integrating various plots and graphs on Tkinter applications is possible through the use of Matplotlib.
Рисование графиков. Python. Tkinter
Это моя первая статья и я хотел бы рассказать о том как написать простейшую программу по рисованию графиков функций.
Статья ориентирована на новичков!
Начнем с того, что наша функция будет иметь вид:
y = c(x)
Где c(x) — это выражение от одной переменной «x».
Сразу считаем её.
Считать значение функции мы будем функцией eval().
Подключим нужные нам библиотеки.
from math import * from tkinter import * f = input('f(x):')
Теперь надо нарисовать оси координат.
from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "lightblue", cursor = "pencil") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) canv.pack() root.mainloop()
Для пересчета значений функции в разных точках я брал 16000 точек на оси X.
Для каждой из них мы считаем значение «y».
Нарисуем овалы с координатами (x, y, x + 1, y + 1).
Овалы, как вы уже, наверное, поняли, — это просто точки на нашем графике.
Перебираем эти точки.
from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "white") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) First_x = -500; for i in range(16000): x = First_x + (1 / 16) * i new_f = f.replace('x', str(x)) y = -eval(new_f) + 500 x += 500 canv.create_oval(x, y, x + 1, y + 1, fill = 'black') canv.pack() root.mainloop()
Итак, мы уже умеем выводить оси координат и график функции на отрезке от -500 до 500.
Но если мы введем функцию, которая не определена в какой — нибудь из проверяемых точек, или она содержит ошибку, то наша программа вылетит с ошибкой, это не есть здорово.
Для того, чтобы исправить это, усовершенствуем наш код.
И разметим наши оси.
from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "white") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) First_x = -500; for i in range(16000): if (i % 800 == 0): k = First_x + (1 / 16) * i canv.create_line(k + 500, -3 + 500, k + 500, 3 + 500, width = 0.5, fill = 'black') canv.create_text(k + 515, -10 + 500, text = str(k), fill="purple", font=("Helvectica", "10")) if (k != 0): canv.create_line(-3 + 500, k + 500, 3 + 500, k + 500, width = 0.5, fill = 'black') canv.create_text(20 + 500, k + 500, text = str(k), fill="purple", font=("Helvectica", "10")) try: x = First_x + (1 / 16) * i new_f = f.replace('x', str(x)) y = -eval(new_f) + 500 x += 500 canv.create_oval(x, y, x + 1, y + 1, fill = 'black') except: pass canv.pack() root.mainloop()
Теперь готово.
Получилась примитивная рисовала графиков.
Using Tkinter and Matplotlib
Recently I was working on a project in which I needed to quickly visualize groups of 2D data points. As the project was in Python, I thought the well-established libraries Tkinter and matplotlib would be useful for this task. Unfortunately, I had to hunt through many sources to figure out how to use these two libraries together, so I am writing this blog post to help others who may have similar needs.
Below is the result from our project:
As you can see we have displayed three groups of data points, each in a different color.
First we will look at setting up the matplotlib environment in Tkinter . Here is a minimal set of necessary import statements.
from tkinter import * from tkinter.ttk import * import matplotlib matplotlib.use("TkAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
For the purposes of this blog post we will create a window with nothing but the matplotlib canvas to make things simpler. Suppose our Tkinter application consists of nothing but the following:
Now we can start creating the matplotlib canvas.
figure = Figure(figsize=(5, 4), dpi=100) plot = figure.add_subplot(1, 1, 1)
There are some options which can be configured here, such as figsize which takes a width by height in inches, and the dpi. We can specify the position of the subplot, here we use (1, 1, 1) as the top-left corner, which will cause the subplot to take up the entire figure.
This doesn’t draw anything to screen yet, in order to do that we need to create an instance of FigureCanvasTkAgg . To the best of my knowledge we will need to do this every time we finish updating the canvas.
canvas = FigureCanvasTkAgg(figure, root) canvas.get_tk_widget().grid(row=0, column=0)
Then of course to begin the application
The code up to this point will draw a blank graph, like this:
Now we can start plotting points on our graph. To do so, we use the plot method on the subplot we created earlier
plot.plot(0.5, 0.3, color="#C41E3A", marker="o", linestyle="")
This will plot a single point at coordinates (0.5, 0.3) . We can also plot multiple points at once by passing separate lists of x and y values.
x = [ 0.1, 0.2, 0.3 ] y = [ -0.1, -0.2, -0.3 ] plot.plot(x, y, color="blue", marker="x", linestyle="")
This will plot the points (0.1, -0.1) , (0.2, -0.2) , and (0.3, -0.3) . For colors, matplotlib features a few built in colors which can be seen here, or you can specify then as a hex triplet. There are many different marker styles to choose from, here is a full list. Finally, by default, matplotlib will connect all points we plot, but we can turn this off by passing an empty linestyle .
Here we drew our points all at once, but if we had drawn them dynamically (e.g. as a result of pressing a button) we would have needed to create the FigureCanvasTkAgg object again and regrid it, as demonstrated above.
So the final code for our graph application:
from tkinter import * from tkinter.ttk import * import matplotlib matplotlib.use("TkAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg root = Tk() figure = Figure(figsize=(5, 4), dpi=100) plot = figure.add_subplot(1, 1, 1) plot.plot(0.5, 0.3, color="red", marker="o", linestyle="") x = [ 0.1, 0.2, 0.3 ] y = [ -0.1, -0.2, -0.3 ] plot.plot(x, y, color="blue", marker="x", linestyle="") canvas = FigureCanvasTkAgg(figure, root) canvas.get_tk_widget().grid(row=0, column=0) root.mainloop()
So that is a quick, simple, and customizable way of visualizing data.
Tkinter Graph
Matplotlib is a plotting library for Python that allows us to create some great-looking graphs from our data; this is used in the data science field and in applications where we need to visualize our data analysis. With Matplotlib, we can make some nice visualizations in Python.
This demonstration will teach how to make charts or graphs using Numpy, Matplotlib, and Tkinter in Python.
Create Matplotlib Graph With Tkinter in Python
So now we want to talk just a little bit about graphs. Python for data analysis is super popular in data science and machine learning.
You always create graphs in Tkinter because people want to add buttons or another widget to generate a graph and add flavor to their Matplotlib graphs; fortunately, we can create graphs with Tkinter in Python.
This article will not discuss using matplotlib or numpy ; we will assume you already know what those libraries are or how to use them and what we are doing with them.
We will focus on taking data that we have been manipulating with those libraries and then specifically throwing it up on the screen with a graph or a chart or something that we can visualize in Tkinter.
It is very easy and should not take very long, so first, we need to install Numpy and Matplotlib. Numpy is what we use to manipulate the data, and Matplotlib is what we use to throw up the graph on the screen, so now we need to install these into our terminal using the following commands.
pip install numpy pip install matplotlib
We need to import numpy , tkinter , and matplotlib into our program. It is really simple; we use the following code.
from tkinter import * import matplotlib.pyplot as plt import numpy as np
We import numpy as np ; this allows us to access numpy by referencing np , instantiating it, and in the same way, we also import matplotlib .
After creating basic things, let’s create a little function called Graph_Generator() . Inside this function, we want to quickly create some data that we can use to make a graph.
We can also import something from a CSV file; if you have data, you can import that. We make some random data to keep it simple, so we call the np.random.normal method from numpy to get the normal distribution for the sample data.
We just passed a few samples of house prices in this method so that the normal distribution will return the average price of a house.