LoginSignup
8

More than 3 years have passed since last update.

posted at

TkinterでEntryに入力したデータが取得出来なかった件

はじめに

pythonでプログラムを組んで、実験で得られるデータを解析・整理することを、最近始めました。
やり出すと欲が出て、ファイル名やデータの入力もGUI形式でやってみよう!と思いたち、作ったところ、なぜかエントリに入力したデータが取得出来ない。。。
いろいろググったのですが、私のやりたい事が載っている記事が見つからなかったので、備忘録として記事にします。

やりたいこと

エントリに入力したデータを取り出す

環境

・Windows 10 PRO
・Python Ver3.7.3
・Microsoft VS Code上で動作確認

最初に書いたコード

GUItest.py
# モジュールのインポート
import os, tkinter, tkinter.filedialog, tkinter.messagebox

# ウインドウ
root = tkinter.Tk()
root.title(u"テストプログラム")
root.geometry("400x300")

# データ数入力
Static1 = tkinter.Label(text=u'データ数')
Static1.place(x=5,y=5)
EditBox1 = tkinter.Entry(width=5)
EditBox1.place(x=100, y=5)

value = EditBox1.get() # エントリに入力されたデータを取得

root.mainloop()

print("value=",value) # データが格納されたことを確認

結果

01.png
02.png
valueの所に値が入っていない。
検索しても検索しても「get()で文字を取得する」としか書いていない・・・
なぜ??

対処法

GUItest1.py
# モジュールのインポート
import os, tkinter, tkinter.filedialog, tkinter.messagebox

def func():
    global value
    print("in the function =",EditBox1.get())
    value = EditBox1.get()

# ウインドウ
root = tkinter.Tk()
root.title(u"テストプログラム")
root.geometry("400x300")

# データ数入力
Static1 = tkinter.Label(text=u'データ数')
Static1.place(x=5,y=5)
EditBox1 = tkinter.Entry(width=5)
EditBox1.place(x=100, y=5)

b = tkinter.Button(text='Exec', command=func)
b.pack()

root.mainloop()

print("value=",value) # データが格納されたことを確認

05.png

何か刺激がないと(?)データが取得できないのではないかと思い、ボタンを付けて、押したときに関数を起動させる様にしたところ、関数側ではデータが取得できる事が分かったので、その値を全体で使えるようにしたら解決した、という事です。

もっといいやり方(正しいやり方?)があるとは思いますが、使えればいいので
(^o^)v

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
What you can do with signing up
8