Tkinterエントリボックスが空かどうかを確認するには?
つまり、値が割り当てられていない場合です。
値を取得して、その長さを確認できます。
if len(the_entry_widget.get()) == 0:
do_something()
ウィジェットの最後の文字のインデックスを取得できます。最後のインデックスが 0 (ゼロ) の場合、それは空です。
if the_entry_widget.index("end") == 0:
do_something()
授業で使った例です。
import Tkinter as tk
#import tkinter as tk (Python 3.4)
class App:
#Initialization
def __init__(self, window):
#Set the var type for your entry
self.entry_var = tk.StringVar()
self.entry_widget = tk.Entry(window, textvariable=self.entry_var).pack()
self.button = tk.Button(window, text='Test', command=self.check).pack()
def check(self):
#Retrieve the value from the entry and store it to a variable
var = self.entry_var.get()
if var == '':
print "The value is not valid"
else:
print "The value is valid"
root = tk.Tk()
obj = App(root)
root.mainloop()
次に、上からのエントリは数字と文字列のみを取ることができます。ユーザーがスペースを入力すると、エラー メッセージが出力されます。入力を整数または浮動小数点数などの形式にしたい場合は、キャストするだけです!
Example:
yourVar = '5'
newVar = float(yourVar)
>>> 5.0
それが役立つことを願っています!