LoginSignup
1
5

More than 1 year has passed since last update.

Pythonチートシート - TKinterウィジェットの使い方一覧

Last updated at Posted at 2023-01-26

Pythonを使ったGUIアプリを作りたいと考え、TKinterウィジェットの使い方一覧をまとめたアプリを作ってみました。後ほど実用的なアプリができたら公開しようと思います。

基礎となるTKinterウィジェット

以下のウィジェットを実際に作って1つのアプリに纏めてみました。
・ラベル、ボタン、インプット、エントリー、テキスト、スピンボックス、スケール
・チェックボックス、ラジオボタン、リストボックス

スクリーンショット 2023-01-26 233414.png

実際のコード

import tkinter as tk

#ウィンドウのタイトル+サイズ
window = tk.Tk()
window.title("GUI Program")
window.minsize(width=500, height=600)

#ボタンなどに使う関数
def button_clicked():
    print("I got clicked!")

    #インプットのテキストを取得 → ラベルのテキストを変更
    new_text = my_input.get()
    my_label.config(text=new_text)

#基礎となるTKinterウィジェット
#ラベル、ボタン、インプット、エントリー、テキスト、スピンボックス、スケール
#チェックボックス、ラジオボタン、リストボックス

#ラベル
#文字型を画面に表示する。label.configメソッド等で内容を変更できる
my_label = tk.Label(text="I am a label", font=("Arial", 24, "bold"))
my_label.pack()
#my_label.pack(side = "left")


#ボタン
#ボタンを押すことで、関数をつかって他のウィジェットを操作する
my_button = tk.Button(text="Click Me!", command=button_clicked)
my_button.pack()


#インプット
#ボタンなどで取得する用の文字列を記載する。
my_input = tk.Entry(width=10)
my_input.pack()
#print(my_input.get())


#エントリー
entry = tk.Entry(width=30)
entry.insert(tk.END, string="Default text")
entry.pack()


#テキスト
text = tk.Text(height=5, width=30)
text.focus()
text.insert(tk.END, "Default text - multiple line entry")
text.pack()


#スピンボックス
#スピンボックスがどの値かを取得する
def spinbox_used():
    print(spinbox.get())
spinbox = tk.Spinbox(from_=0, to=10, width=5, command=spinbox_used)
spinbox.pack()


#スケール
#スケールがどの値かを取得する
def scale_used(value):
    print(value)
scale = tk.Scale(from_=0, to=10, width=20, command=scale_used, orient=tk.HORIZONTAL, variable = 5)
scale.pack()

#チェックボタン
def checkbutton_used():
    print(checked_state.get())

checked_state = tk.IntVar()
checkbutton = tk.Checkbutton(text="Is on?", variable=checked_state, command=checkbutton_used)
checked_state.get()
checkbutton.pack()


#ラジオボタン
#ラジオボタンに割り振られた変数を関数で処理する際に使う
def radio_used():
    print(radio_state.get())

radio_state = tk.IntVar()
radiobutton01 = tk.Radiobutton(text="Option01", value=1, variable=radio_state, command=radio_used)
radiobutton01.pack()

radiobutton02 = tk.Radiobutton(text="Option02", value=2, variable=radio_state, command=radio_used)
radiobutton02.pack()


#リストボックス
def listbox_used(event):
    print(listbox.get(listbox.curselection()))

listbox = tk.Listbox(height=4)
fruits = ["Apple","Pear","Orange","Banana"]
for item in fruits:
    listbox.insert(fruits.index(item),item)

listbox.bind("<<ListBoxSelect>>", listbox_used)
listbox.pack()
window.mainloop()

#メインループを実行
window.mainloop()


1
5
0

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
1
5