2017-04-01 136 views
0

我想做一个函数,将文本添加到文本框,如果它后面的变量是空的。我试图做到这一点使用.LEN()函数,但我得到一个找到一个字符串的长度

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

不是'len(line1var)'工作吗? – ForceBru

+0

@ForceBru:No.'TypeError:'StringVar'类型的对象没有len()'。但是你可以'如果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() 

BTW,你应该

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

.pack方法(和相关.grid.place方法)返回None,因此上面的语句将None指定为foo。要将小工具分配到foo,您需要在单独的语句中执行分配和打包,例如

foo = Button(root, text="foo", command=lambda : tobeplaced("foo")) 
foo.pack() 
相关问题