Tkinter Entry组件get函数无返回值问题求助
问题分析与解决办法
你的代码里有几个关键问题导致Entry组件的get()方法无法返回内容,以下是具体修正方案:
核心问题点
- Entry的textvariable传参错误:你给
textvariable传的是字符串(比如"courseN"),但Tkinter需要绑定的是实际的StringVar对象(不带引号的courseN),否则无法关联输入内容。 - 布局与组件创建连写导致变量失效:
Entry(...).place(...)这种写法中,place()返回None,所以course_name这类变量实际是None,虽然不影响textvariable取值,但分开写是规范的组件操作方式。 - 条件判断逻辑错误:你用
or判断字段是否为空,意思是只要有一个字段不为空就提示成功,这和“所有字段必须填写”的需求相反,应该改成and。 - 布局方式混用:
DateEntry用pack,其他组件用place,会导致布局混乱,建议统一布局方式。
修正后的完整代码
from functools import partial from tkinter import * from tkinter import messagebox from tkcalendar import Calendar, DateEntry def attend(courseN, topicN, studN): ca = courseN.get() ta = topicN.get() sname = studN.get() # 改为and,确保所有字段都不为空才触发成功提示 if ca != "" and ta != "" and sname != "": messagebox.showinfo("success", "all fields saved") print("hello") else: print("printing") messagebox.showinfo("error", "please enter all fields") if __name__=="__main__": top = Tk() top.geometry("450x300") # 创建标签 Label(top, text="Date").place(x=40, y=22) Label(top, text="Course").place(x=40, y=60) Label(top, text="Topic").place(x=40, y=100) Label(top, text="Students present").place(x=40, y=140) # 定义绑定用的StringVar对象 courseN = StringVar() topicN = StringVar() studN = StringVar() # DateEntry改用place布局,和其他组件统一 date = DateEntry(top, width=16, background="magenta3", foreground="white", bd=2) date.place(x=150, y=22) # 拆分Entry组件创建与布局,textvariable绑定实际对象 course_name = Entry(top, width=30, textvariable=courseN) course_name.place(x=150, y=60) topic_name = Entry(top, width=30, textvariable=topicN) topic_name.place(x=150, y=100) student_name = Entry(top, width=30, textvariable=studN) student_name.place(x=150, y=140) # 避免覆盖原函数名,重命名partial生成的对象 attend_func = partial(attend, courseN, topicN, studN) submit_button = Button(top, text="Submit", command=attend_func) submit_button.place(x=120, y=180) top.mainloop()
关键修改说明
- textvariable绑定修正:把
textvariable="courseN"改为textvariable=courseN,让Entry组件和对应的StringVar对象关联,确保get()能拿到输入内容。 - 组件与布局拆分:先创建Entry组件并赋值给变量,再调用
place()布局,保留组件引用方便后续操作。 - 条件判断逻辑调整:将
or替换为and,符合“所有字段必填”的业务逻辑。 - 统一布局方式:
DateEntry改用place布局,避免不同布局方法混用导致的界面错位。
内容的提问来源于stack exchange,提问作者Pradhumn charde
相关产品推荐
相关产品推荐

