Python:使用按钮获取 Tkinter 的条目值时出错 [英] Python: Error in getting Tkinter's Entry value with button

查看:30
本文介绍了Python:使用按钮获取 Tkinter 的条目值时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,因为这是我学习 Python 的第一天,我希望人们不要介意新手问题

Well since this is my first day learning Python I hope people don't mind for newbie question

我有一个带有 GUI 布局的 Tkinter,如下所示:

I have a Tkinter with GUI layout like this:

Label(base, text="Site URL: ",width=15).grid(row=0,column=0,sticky=STICKY,pady=5)
entry1 = Entry(base, width=40).grid(row=0,column=1,sticky=STICKY,pady=5)
mybtn = Button(base, text="Run",command=s.initiate(entry1.get())).grid(row=0,column=2,sticky=STICKY,padx=10,pady=5)

STICKY 是用于网格布局的 N+S+E+Ws.initiate 中的 s 是我这样导入的模块(在我的主文件顶部):

STICKY is N+S+E+W for grid layout, s from s.initiate is a module I imported like this (on the top of my main file):

import spider as s

spider模块内容是这样的:

import tkMessageBox

def initiate(url):
    tkMessageBox.showinfo("Spider", url)

当我尝试编译我的代码时出现此错误:

when I'm trying to compile my code this error comes out:

File "index.py", line 18, in <module>
  mybtn = Button(base, text="Run",command=s.initiate(entry1.get())).grid(row=0,column=2,sticky=STICKY,padx=10,pady=5)
AttributeError: 'NoneType' object has no attribute 'get'

谁能解释我在点击按钮时从 Entry 获取价值时做错了什么?

Can anyone explain what I'm doing wrong in getting value from Entry on button click?

我的猜测是 get() 在编译代码时正在运行,但 entry1 尚未通过 Python 注册到 Tkinter gui.如果这是真的,谁能告诉我一个解决方法?

My guess is get() is being run while compiling the code, but entry1 has not been registered to the Tkinter gui by Python yet. If this is true, can anyone show me a workaround from this?

推荐答案

尝试这样做:

entry1=Entry(base, width=40)
entry1.grid(row=0,column=1,sticky=STICKY,pady=5)

问题是您使用的变量的值为 None &当你执行 None.get() 时,你会得到一个错误.它的值为 None 因为 entry1 具有最后调用的函数的值,即 grid() 总是返回 None.

The problem is you are using a variable whose value is None & when you do None.get(), you get an error. Its value is None because entry1 has the value of the last function called,which was grid() which always returns None.

函数的自动调用是因为你正在调用它.如果您想向函数发送一些参数,请执行以下操作:

The automatic calling of function is because you are calling it. If you want to send some arguments to a function, do this:

command=lambda:myfunc(myargs)

另外,如果你不想发送任何参数,简单的 command=myfunc 就足够了(注意这里没有括号)

Also, if you don't want to send any arguments the simple command=myfunc would suffice(Notice that there are no parenthesis here)

这篇关于Python:使用按钮获取 Tkinter 的条目值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆