为什么它在python shell中返回none

时间:2017-03-17 22:41:45

标签: python text tkinter

我正在尝试创建一个程序,它只允许您在使用文本框时将一定数量的字符写为提示。当我尝试运行程序时,它在python shell中返回none并且没有完成我想要的功能。我想写它"你的提示已经发布了#34;如果有不到十个字符并写'#34;提示太长"如果有超过10个字符。在此先感谢您的帮助。非常感谢

label = Label(tk, text="Prompt:")
label.place(relx=0.1, rely=0.2, anchor=CENTER)
text = Text(tk, width=50, height=6, bg="gray")
text.place(relx=0.62, rely=0.2, anchor=CENTER)

def diary():
    print("Why does this not work")

def begin():
    while True:
        answer = input(text.insert(INSERT, diary))
        if len(answer) <= 10:
           print("Your prompt has been posted")
        else:
           print("The prompt is too long")


button = Button(tk, text="Submit", command=begin)
button.place(relx=0.5, rely=0.5, anchor=CENTER)

1 个答案:

答案 0 :(得分:1)

代码永远不会结束,因为你告诉它永远运行一个循环而不会改变任何导致它停止的东西。

此外,无论您认为此代码在做什么,它可能都没有这样做。我认为这一行代码至少有三个问题:

answer = input(text.insert(INSERT, diary))

input命令将从命令行(技术上,stdin)读入,这不是您通常在GUI中执行的操作。您正在将调用结果传递给text.insert,但text.insert未记录以返回任何内容。另外,您要为text.insert提供一个需要字符串的函数。

如果要插入函数diary返回的内容,则必须a)定义diary来执行某些操作,并且b)作为函数调用。例如:

def diary():
    return "something"
...
text.insert(INSERT, diary())

如果您的真正目标是让begin获取用户在GUI中输入的内容并检查长度,那么您需要删除while循环并将insert的调用替换为{{ 1}}:

get