LoginSignup
0
3

More than 3 years have passed since last update.

Tkinterを使ってみる

Last updated at Posted at 2020-02-11

PythonでGUIプログラムを書けるTkinterを使ってみる。

Tkinter

PythonでGUIアプリケーションを作成できるライブラリ。Pythonに標準で入っているため、特にインストールなどはせずに使用可能。

サンプルコード

# -*- coding : utf-8 -*-
u"""
GUIプログラミングのサンプル
"""
import tkinter
from tkinter import messagebox

def button_push(event):
    u"ボタンをクリックされたときの動作"
    edit_box.delete(0, tkinter.END)

def func_check(event):
    u"チェックボックスの状態を確認して、表示する"
    global val1
    global val2
    global val3

    text = ""

    if val1.get() == True:
        text += "項目1はチェックされています\n"
    else:
        text += "項目1はチェックされていません\n"
    if val2.get() == True:
        text += "項目2はチェックされています\n"
    else:
        text += "項目2はチェックされていません\n"
    if val3.get() == True:
        text += "項目3はチェックされています\n"
    else:
        text += "項目3はチェックされていません\n"

    messagebox.showinfo("info", text)


if __name__ == "__main__":
    root = tkinter.Tk()
    root.title(u"GUIサンプル")
    root.geometry("400x300")

    # テキストボックス
    edit_box = tkinter.Entry(width=50)
    edit_box.insert(tkinter.END, "サンプル文字列")
    edit_box.pack()

    # ボタン
    button = tkinter.Button(text=u"消去", width=30)
    button.bind("<Button-1>", button_push)
    button.pack()
    # button.place(x=105, y=30)

    # チェックボックス
    val1 = tkinter.BooleanVar()
    val2 = tkinter.BooleanVar()
    val3 = tkinter.BooleanVar()
    val1.set(False)
    val2.set(True)
    val3.set(False)
    checkbox1 = tkinter.Checkbutton(text=u"チェック1", variable=val1)
    checkbox1.pack()
    checkbox2 = tkinter.Checkbutton(text=u"チェック2", variable=val2)
    checkbox2.pack()
    checkbox3 = tkinter.Checkbutton(text=u"チェック3", variable=val3)
    checkbox3.pack()

    # ボタン
    button2 = tkinter.Button(root, text=u"チェックボックスの取得", width=50)
    button2.bind("<Button-1>", func_check)
    button2.pack()

    tkinter.mainloop()

実行例

1a72ae3c.png

参照

0
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3