Tkinter按钮调用函数报错:'Application'对象无'hi'属性求助
解决Tkinter中'Application'对象无'hi'属性的错误
问题根源在于你把hi函数定义在了__init__方法内部,它只是__init__的局部函数,不属于Application类的成员方法,因此按钮点击时调用self.hi会触发属性错误。
修正方法很简单,将hi函数移到__init__方法外面,作为Application类的独立成员方法即可:
from tkinter import * import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() class Application: def __init__(self, master): self.master = master self.left = Frame(master, width=800, height=720, bg='lightgreen') self.left.pack(side=LEFT) self.right = Frame(master, width=400, height=720, bg='lightblue') self.right.pack(side=RIGHT) self.heading=Label(self.left,text="HM hospital Appointments",font=('arial 40 bold'),fg='white',bg='lightgreen') self.heading.place(x=0,y=0) self.name=Label(self.left,text="Patient Name",font=('arial 20 italic'),fg='black',bg='lightgreen') self.name.place(x=0,y=100) self.age=Label(self.left,text="Age",font=('arial 20 italic'),fg='black',bg='lightgreen') self.age.place(x=0,y=150) self.gender=Label(self.left,text="Gender",font=('arial 20 italic'),fg='black',bg='lightgreen') self.gender.place(x=0,y=200) self.location=Label(self.left,text="Location",font=('arial 20 italic'),fg='black',bg='lightgreen') self.location.place(x=0,y=250) self.time=Label(self.left,text="Appointment Time",font=('arial 20 italic'),fg='black',bg='lightgreen') self.time.place(x=0,y=300) self.name_ent=Entry(self.left,width=30) self.name_ent.place(x=250,y=110) self.age_ent=Entry(self.left,width=30) self.age_ent.place(x=250,y=160) self.gender_ent=Entry(self.left,width=30) self.gender_ent.place(x=250,y=210) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250,y=260) self.time_ent=Entry(self.left,width=30) self.time_ent.place(x=250,y=310) self.submit=Button(self.left,text="Add appointment",width=20,height=2,bg='steelblue',command=self.hi) self.submit.place(x=300,y=350) def hi(self): self.val1=self.name_ent.get() # 可在此添加保存到数据库等逻辑 print(self.val1) # 测试是否成功获取输入值 root = Tk() b = Application(root) root.geometry("1200x720+0+0") root.resizable(False, False) root.mainloop()
关键修改点:
- 将原本在
__init__内部的hi函数移出,缩进调整到和__init__同级,成为类的成员方法 - 可在
hi方法中添加测试打印,验证是否能正常获取输入框内容
内容的提问来源于stack exchange,提问作者Amal
相关产品推荐
相关产品推荐

