LoginSignup
3

More than 3 years have passed since last update.

PythonのtkinterでGUIを作ってみる

Last updated at Posted at 2019-09-08

GUIに挑戦してみる

プログラムをいろいろ作っているうちに

「コマンドプロンプト(黒い画面)じゃなくてGUIのほうがイカしてるじゃん。」

って思ったので作ってみました。
(あいかわらず動機がしょうもない…)

tkinterという便利なやつ

んで、もちろんPythonさんなわけですが
なんか標準で入ってるやつがあるみたいです。
ありがたいですね。

import tkinter
import tkinter.messagebox

ほかにもGUIのライブラリはあるみたいですが
標準があるなら標準でいきましょう。
標準最高です。

ひとまず完成

import sys
import tkinter
import tkinter.messagebox

#ボタンイベント
def btn_click():
    xxxx = str(txt.get())
    if len(xxxx) == 0:
        tkinter.messagebox.showinfo('入力内容','何も入力されてないよ?')
        root.mainloop()       
    else:
        tkinter.messagebox.showinfo('入力内容','「 '+xxxx+' 」 が入力されました!')
        root.quit()
        root.destroy()

# tkクラス生成
root = tkinter.Tk()
# 画面サイズ()
w = 600
h = 300
wh = str(w)+'x'+str(h)#ここは小文字のxじゃなきゃだめ
root.geometry(wh)
# 画面出現位置
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
sw = (screen_width-w)/2
sh = (screen_height-h)/2
sw ='{0:.0f}'.format(sw)
sh ='{0:.0f}'.format(sh)
swstr = '+'+str(sw)
shstr = '+'+str(sh)
root.geometry(swstr+shstr)
# 画面タイトル
root.title('はじめてのGUI')
# ラベル
lbl = tkinter.Label(text='1.なんか入力して下さい')
lbl.place(x=30, y=80)
# テキストボックス
txt = tkinter.Entry(width=50)
txt.place(x=30, y=100)
# ボタン
btn = tkinter.Button(root, text='表示', command = btn_click)
btn.place(x=280, y=230)
#ウィンドウ表示 
root.mainloop()

はいできた~。
わりと簡単でした。

ちょっと気になる点

実は作ってみて「んー、わからん」というところがありました。
自分はここで入力された内容を変数として保持したいんですが
関数内の処理結果は保持できないのでどうすればいいのか?
(globalをつかって切り抜けはしましたが納得いかない…)
解決方法がわかる人がいたら教えてほしいです。

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
3