非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

Pythonの標準GUI Tkinterを試してみた

   

以前、PythonのGUIツールキットとしてPyQtを使いました。

QtもAnacondaに同梱されてはいるのですが、標準GUIとしてTkinterというライブラリがあるので試してみました。

[ad#top-1]

Tkinterがインストールされているか確認

標準ライブラリとはいえ、プログラミング前にちゃんとインストールされているか確認しましょう。

コンソールから以下のコマンドを打って確認してください。

python3 -m tkinter
 

 

以下のようなウィンドウが現れたらちゃんとインストールされています。

Tkinterを使ってみよう

以下のコードを書いて実行してみましょう。

import tkinter as tk

root = tk.Tk()
root.title(u"Thinter Test")
root.geometry("400x300")

root.mainloop()
 

 

以下のように400×300のまっさらなウィンドウが現れます。まずはこれが基本ですね。

 

ボタンの配置

root.mainloop()の前に以下のコードを追加すると3つのボタンが現れます。

btn1 = tk.Button(root, text="Button1", width="20")
btn1.place(x=10, y=10)
btn2 = tk.Button(root, text="Button2", width="20")
btn2.place(x=10, y=40)
btn3 = tk.Button(root, text="Button3", width="20")
btn3.place(x=10, y=70)
 

 

ご覧のとおりです。縦に幅20のボタンが現れました。

ボタンを押したらイベントを発生させる

Buttonの引数にcommand=<em>関数名</em>を入れることでイベント処理が可能になります。

def push1():
  print("push1")
def push2():
  print("push2")
def push3():
  print("push3")

btn1 = tk.Button(root, text="Button1", width="20", command=push1)
btn1.place(x=10, y=10)
btn2 = tk.Button(root, text="Button2", width="20", command=push2)
btn2.place(x=10, y=40)
btn3 = tk.Button(root, text="Button3", width="20", command=push3)
btn3.place(x=10, y=70)
 

 

実行するとコンソールに以下のように出力されるようになりました。

 

1行テキストボックス

1行テキストボックスはEntryを使います。

textBox = tk.Entry(root)
textBox.place(x=200, y=10)
 

 

更にボタンを押すことでテキストボックスに文字が入るようなイベントを仕込んでおきます。

def push1():
  textBox.delete(0, tk.END)
  textBox.insert(tk.END,"push1")
 

 

以下の通りボタンを押すことでテキストボックスに文字が入るようになりました。

 

ソースコード全文は以下のとおりです。

import tkinter as tk

root = tk.Tk()
root.title(u"Thinter Test")
root.geometry("400x300")

def push1():
  textBox.delete(0, tk.END)
  textBox.insert(tk.END,"push1")
def push2():
  print("push2")
def push3():
  print("push3")

btn1 = tk.Button(root, text="Button1", width="20", command=push1)
btn1.place(x=10, y=10)
btn2 = tk.Button(root, text="Button2", width="20", command=push2)
btn2.place(x=10, y=40)
btn3 = tk.Button(root, text="Button3", width="20", command=push3)
btn3.place(x=10, y=70)

textBox = tk.Entry(root)
textBox.place(x=200, y=10)

root.mainloop()
 

 

[ad#ad-1]

スポンサーリンク

 - Python