Tkinter报错Unknown option "-text":按钮触发数据库文本显示问题
解决Tkinter报错
TclError: unknown option "-text" 报错原因及修复步骤:
Text组件不支持
text初始化参数
Tkinter的Text控件不能在初始化时通过text参数设置内容,必须使用insert()方法插入文本。拼写错误
TextBox类的place方法里把location拼写成了loaction,修正拼写即可。数据库查询未获取结果
c.execute()仅返回查询游标,不会直接得到数据,需要调用fetchone()或fetchall()提取查询结果。按钮命令绑定错误
直接写display_info('EGSL')会导致程序启动时就执行该函数,应该用lambda包装,确保点击按钮时才触发。
修复后的完整代码
import tkinter as tk import sqlite3 # 初始化数据库连接(示例) conn = sqlite3.connect('your_database.db') c = conn.cursor() root = tk.Tk() root.geometry("800x500") vfr_import = tk.PhotoImage(file="Images/vfr.png") r_vfr = vfr_import.subsample(3, 3) class Airfields(tk.Button): def __init__(self, master, image, command, location): super().__init__(master, image=image, command=command) self.style = {"bg":"#7D7D7D","bd":0,"highlightbackground":"#7D7D7D","highlightthickness":0} self.place(x=location[0], y=location[1]) self.config(self.style) class TextBox(tk.Text): def __init__(self, master, text, location): super().__init__(master) self.style = {"bg":"Black","font":("Arial", 12), "fg":"white"} # 增加前景色便于查看文本 self.place(x=location[0], y=location[1], width=200, height=50) # 建议设置控件宽高 self.config(self.style) # 使用insert方法插入文本 self.insert(tk.END, text) def display_info(location): # 执行查询并获取结果 c.execute("SELECT Name FROM Airfields WHERE ICAO = ?", (location,)) result = c.fetchone() # 处理查询为空的情况 name_text = result[0] if result else "未找到该机场信息" TextBox(root, name_text, [500,300]) # 用lambda包装命令,确保点击按钮时才执行函数 Andrewsfield = Airfields(root, r_vfr, lambda: display_info('EGSL'), [255, 375]) root.mainloop() # 程序结束时关闭数据库连接 conn.close()
内容的提问来源于stack exchange,提问作者golem
相关产品推荐
相关产品推荐

