2017-04-01 6 views
0

私は、その背後にある変数が空の場合にテキストをテキストボックスに追加する関数を作ろうとしています。私はこの.LENを使用して()関数を実行しようとしましたが、私は次のようにstringvarの長さを見つける

AttributeError: 'StringVar' object has no attribute 'length'. 

私のコードがある取得:

line1var = StringVar() 

line1var.set("") 

def tobeplaced(value): 

    global line1var 

    if line1var.length() == 0: 

     txtReceipt.insert(END, value) 

foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack() 

何をしますか?

+1

は '(line1var)lenは'動作しませんか? – ForceBru

+0

@ForceBru:いいえ 'TypeError:タイプ 'StringVar'のオブジェクトにはlen()がありません。しかし、if len(line1var.get())== 0: 'を実行することはできますが、私は' line1var.get(): 'ではなく' 'を優先します。 –

答えて

2

A Tkinter StringVarは、.lenまたは.lengthメソッドを持たない。あなたはgetメソッドに関連付けられた文字列にアクセスして、ビルトインlen機能標準のPythonと、その文字列の長さを取得し、例えば

if len(line1var.get()) == 0: 

が、それはクリーン(かつ効率的)だ

if not line1var.get(): 
を行うことができ

空文字列がfalse-ishなので

はここで小さな(Pythonの3)のデモです:、あなたがないやるべきところで

import tkinter as tk 

root = tk.Tk() 

label_text = tk.StringVar() 
label = tk.Label(textvariable=label_text) 
label.pack() 

def update(): 
    text = label_text.get() 
    if not text: 
     text = 'base' 
    else: 
     text += '.' 
    label_text.set(text) 

b = tk.Button(root, text='update', command=update) 
b.pack() 

root.mainloop() 

foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack() 

.pack方法(および関連.grid.place方法) Noneを返すので、上記のステートメントはNonefooに割り当てます。あなたが代入し、別々のステートメントで梱包を行う必要がありfooにウィジェットを、割り当てるには例えば

foo = Button(root, text="foo", command=lambda : tobeplaced("foo")) 
foo.pack() 
関連する問題