Creating a GUI as easily as possible with python [tkinter edition]

Create UI using tkinter which is included by default in python Receive actions on the operation screen and connect them to processing I want to make the hyperparameters of deep learning selectable so that even people who are not familiar with it can play with it.

Simplest code: Launch window

import tkinter

root = tkinter.Tk()
root.title("Take it")
root.resizable(False, False)
root.geometry("400x200")


#I will add here

root.mainloop()

The window will be launched.

Operate resizable and non-resizable with resizable Adjust drawing size with geometry Execute the contents set as root in the main loop

Based on this, we will add Gacha Gacha

キャプチャ.PNG

Character arrangement


label = tkinter.Label(root, text="label", font=("System",24))
label.place(x=200, y=100)

aaa.PNG

Check the placement of the check button and whether it is checked

import tkinter


def check():
    if cval.get() == True:
        print("yes")
    else:
        print("no")


root = tkinter.Tk()
root.geometry("400x200")


cval = tkinter.BooleanVar()
cval.set(False)

cbtn = tkinter.Checkbutton(text="button", variabl=cval, command = check)
cbtn.pack()


root.mainloop()

Initially set to unchecked state with BooleanVar You can check if it is checked with get (). If you want to move an arbitrary function when the button is pressed, specify the function with command

With this code, yes and no are returned every time I check it on the command line or on the notebook.

dasa.PNG

Definition of pushbutton placement and functions that react when pressed

import tkinter
import tkinter.font

def click_btn():
    button["text"] = "I clicked"

root = tkinter.Tk()
root.title("title")
root.geometry("400x200")


button = tkinter.Button(root, text="button", font=("Times New Roman", 24), command=click_btn)
button.place(x=100,y=100)

root.mainloop()

ffff.PNG

Place pushbuttons with Button Define a function to put a value in the text argument in button font can also be specified

If you want to check the fonts that can be specified,

import tkinter.font

root = tkinter.Tk()
tkinter.font.families()

ddsss.PNG

The displayed characters change when the button is pressed

import tkinter
import random

def click_btn():
    label["text"] = random.choice(["Good morning","Hello","Good evening"])
    label.update()

root = tkinter.Tk()
root.title("title")
root.geometry("400x200")
root.resizable(False, False)

label = tkinter.Label(root, text="Press to display here", font=("Times New Roman", 15), bg = "white")
label.place(x=10, y=10)

button = tkinter.Button(root, text="push button", font=("Times New Roman", 15),command = click_btn, fg = "skyblue")
button.place(x = 50, y = 50)

root.mainloop()

"Press to display here" is included in the label. I want to execute a function that updates the text argument by pressing the button, so specify it as command and have it executed

5452.PNG

Press the button and a message box will appear

import tkinter
import tkinter.messagebox

def click_btn():
    tkinter.messagebox.showinfo("Another window", "Display content")

root = tkinter.Tk()
root.title("Take it")
root.resizable(False, False)
root.geometry("400x200")

button = tkinter.Button(root, text="button", font=("Times New Roman", 24), command=click_btn)
button.place(x=100,y=100)

root.mainloop()

hhhh.PNG

Set up a manual input frame and get the manual input contents with get

import tkinter

def click_btn():
    txt = entry.get()
    button["text"] = txt

root = tkinter.Tk()
root.resizable(False, False)
root.geometry("400x200")


entry = tkinter.Entry(width=20)
entry.place(x=20,y=20)

button = tkinter.Button(root, text="Soak up what you wrote as the name of the button", font=("Times New Roman", 15),command = click_btn)
button.place(x = 20, y = 100)

root.mainloop()

fffddg.PNG

Input frame can be installed with Entry Multiple lines have different functions Since the content entered in Entry can be acquired with the get function, it will be reflected in the button display after acquisition.

Create an image drawing area and display the image

import tkinter
import tkinter.font
from PIL import ImageTk, Image

root = tkinter.Tk()
root.title("title")
root.geometry("600x500")


image = Image.open("Avocado.png ")

canvas = tkinter.Canvas(root, width=500, height=400, bg="black")
canvas.pack()

photo = ImageTk.PhotoImage(image, master=root)
canvas.create_image(100, 100, image=photo)

root.mainloop()

Create a drawing area of the specified size from the center of the window Specify the position of create_image with the upper left of the drawing area as 0,0 The center of the image is specified

cavas.PNG

Display matplot in multiple drawing areas

Draw from matplot to tkinter using FigureCanvasTkAgg Displayed in order

import tkinter as tk
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root= tk.Tk() 
root.geometry("1500x500")

figure1 = plt.Figure(figsize=(5,5), dpi=100)
ax1 = figure1.add_subplot(1,1,1)
bar1 = FigureCanvasTkAgg(figure1, root)
bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
df1 = df.groupby('target').sum()
df1.plot(kind='bar', legend=True, ax=ax1)
ax1.set_xticklabels(labels=df1.index,rotation=45)
ax1.set_title('fig1 title')

figure2 = plt.Figure(figsize=(5,5), dpi=100)
ax2 = figure2.add_subplot(1,1,1)
line2 = FigureCanvasTkAgg(figure2, root)
line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
df2 = df.groupby('target').sum()
df2.plot(kind='line', legend=True, ax=ax2, color='r',marker='o', fontsize=10)
ax2.set_title('fig2 title')

figure3 = plt.Figure(figsize=(5,5), dpi=100)
ax3 = figure3.add_subplot(1,1,1)
ax3.scatter(df['sepal length (cm)'],df['petal length (cm)'], color = 'g')
scatter3 = FigureCanvasTkAgg(figure3, root) 
scatter3.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
ax3.set_ylabel('xlab')
ax3.set_xlabel('xlab')
ax3.set_title('fig3 title')

root.mainloop()

image.png

Move the displayed image from the keyboard operation

Use KeyPress etc. to receive keyboard operations I will also try to get the contents of keyboard operation

Specify the image position by attaching a tag to the image you want to move The after function reflects the function specified at the end while using a delay of 1000 = 1 second.

import tkinter
from PIL import ImageTk, Image

key = ""

def key_down(e):
    global key
    key = e.keysym
    label["text"] = ("your key log = "+ key)

def key_up(e):
    global key
    key = ""

cx = 400
cy = 300

def main_proc():
    global cx, cy
    if key == "Up":
        cy = cy -20
    if key == "Down":
        cy = cy + 20
    if key == "Left":
        cx = cx - 20
    if key =="Right":
        cx = cx + 20
    canvas.coords("MYpicture", cx,cy)
    root.after(100, main_proc)

log=""

def puss(e):
    global log
    log = e.keysym


    
root = tkinter.Tk()

root.bind("<KeyPress>", key_down)
root.bind("<KeyRelease>", key_up)

canvas = tkinter.Canvas(width=800, height=600,bg="lightgreen")
canvas.pack()

image = Image.open("Avocado.png ")
photo = ImageTk.PhotoImage(image, master=root)
canvas.create_image(cx, cy, image=photo, tag="MYpicture")

label = tkinter.Label(font=("System",24))
label.pack()

main_proc()

root.mainloop()

des.gif

Code to get the mouse position

import tkinter

mouse_x = 0
mouse_y = 0
mouse_c = 0

def mouse_move(e):
    global mouse_x, mouse_y
    mouse_x = e.x
    mouse_y = e.y

def mouse_press(e):
    global mouse_c
    mouse_c = 1

def mouse_release(e):
    global mouse_c
    mouse_c = 0

def game_main():
    fnt = ("Times New Roman", 30)
    txt = "mouse({},{}){}".format(mouse_x, mouse_y, mouse_c)
    cvs.delete("TEST")
    cvs.create_text(456, 384, text=txt, fill="black", font=fnt, tag="TEST")
    root.after(100, game_main)

root = tkinter.Tk()
root.title("Mouse input")
root.resizable(False, False)
root.bind("<Motion>", mouse_move)
root.bind("<ButtonPress>", mouse_press)
root.bind("<ButtonRelease>", mouse_release)
cvs = tkinter.Canvas(root, width=912, height=768)
cvs.pack()
game_main()
root.mainloop()

deskk.gif

that's all

I think that you can draw the input contents by combining with button and entry, and you can pull the function in the package by using command.

[Game development made with Python](https://www.amazon.co.jp/Python%E3%81%A7%E3%81%A4%E3%81%8F%E3%82%8B-%E3%82 % B2% E3% 83% BC% E3% 83% A0% E9% 96% 8B% E7% 99% BA-% E5% 85% A5% E9% 96% 80% E8% AC% 9B% E5% BA% A7-% E5% BB% A3% E7% 80% AC-% E8% B1% AA / dp / 4800712394)

How to Place Matplotlib

Recommended Posts

Creating a GUI as easily as possible with python [tkinter edition]
You can easily create a GUI with Python
Create a python GUI using tkinter
Let's make a GUI with python.
[Python] Creating multiple windows with Tkinter
Creating a simple PowerPoint file with Python
Install Python as a Framework with pyenv
Create a GUI app with Python's Tkinter
Solve optimization problems with quantum annealing based on Python as easily as possible
Create a frame with transparent background with tkinter [Python]
I made a GUI application with Python + PyQt5
Create a GUI executable file created with tkinter
GUI image cropping tool made with Python + Tkinter
Procedure for creating a LineBot made with Python
[Python] I made a Youtube Downloader with Tkinter.
Commands for creating a python3 environment with virtualenv
Create a Python console application easily with Click
Open a file dialog with a python GUI (tkinter.filedialog)
I tried to explain what a Python generator is for as easily as possible.
A * algorithm (Python edition)
Easily beep with python
Create a native GUI app with Py2app and Tkinter
Why not create a stylish table easily with Python?
Problems when creating a csv-json conversion tool with python
[Python] Create a Tkinter program distribution file with cx_Freeze
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
I made a simple typing game with tkinter in Python
Easily serverless with Python with chalice
[Python] Create a file & folder path specification screen with tkinter
Creating GUI tools with pyinstaller
[GUI with Python] PyQt5-Layout management-
Make a fortune with Python
Run Label with tkinter [Python]
I made a puzzle game (like) with Tkinter in Python
I tried to make GUI tic-tac-toe with Python and Tkinter
Create a directory with python
[GUI with Python] PyQt5 -Preparation-
Easily cProfile with a decorator
[GUI with Python] PyQt5 -Paint-
[Short sentence] easygui for those who want to use a simple GUI with Python very easily
I made a library to easily read config files with Python
Save the result of the life game as a gif with python
Try to make capture software with as high accuracy as possible with python (1)
[Python] What is a with statement?
Use pymol as a python library
Solve ABC163 A ~ C with Python
Operate a receipt printer with python
A python graphing manual with Matplotlib.
[GUI with Python] PyQt5 -Widget II-
Creating a decision tree with scikit-learn
Creating a Flask server with Docker
Easily implement subcommands with python click
Solve ABC166 A ~ D with Python
Easily handle lists with python + sqlite3
Create a virtual environment with Python!
I made a fortune with Python.
[GUI with Python] PyQt5-The first step-
Building a virtual environment with Python 3
Easy GUI app with Tkinter Text
Creating a simple app with flask
[GUI with Python] PyQt5-Drag and drop-