如何使Tkinter Text组件每行开头自动添加双空格?
解决Tkinter Text组件菜单内容贴近边缘的问题
方案一:用Text标签设置自动缩进(推荐)
Tkinter的Text组件支持通过标签设置段落缩进,不用手动修改每个插入的文本,就能让所有内容自动远离边缘。
实现步骤:
- 初始化Text组件时,创建一个缩进标签,设置
lmargin1(首行缩进)和lmargin2(换行后缩进)的数值,对应双空格的宽度(可根据字体调整,18号字体设30左右即可)。 - 插入完所有内容后,给整个文本范围添加这个标签即可。
修改后的完整代码:
import tkinter as tk # 注意:cur为数据库游标,需自行完成数据库连接初始化 items = tk.Text(bg='black', font=('Baskerville', 18), wrap=tk.WORD, height=20) # 创建缩进标签,数值可根据实际显示效果调整 items.tag_config('indent', lmargin1=30, lmargin2=30) items.grid(column=0, row=2, columnspan=4, padx=15, pady=10) # 打印菜单条目 def printItems(course): global exportCourse exportCourse = course items.config(state='normal') # 根据饮食偏好筛选菜单 query = 'Select Item,Price,Description FROM {} where Item is Not Null' if vegan_choice_intvar.get() == 1: query += ' and Vegan = "Yes"' if veg_choice_intvar.get() == 1: query += ' and Vegetarian = "Yes"' if soy_choice_intvar.get() == 1: query += ' and ContainsSoy = "No"' if nuts_choice_intvar.get() == 1: query += ' and ContainsNuts = "No"' if milk_choice_intvar.get() == 1: query += ' and ContainsMilk = "No"' if fish_choice_intvar.get() == 1: query += ' and ContainsFish = "No"' # 获取条目数量 cur.execute("select count(Item) from {}".format("Menu" + course)) n = cur.fetchone()[0] # 处理空列表情况 if n == 0: items.delete(1.0,'end') items.insert(tk.END,'\n\n\n\n\n\n\n\n\n\n No Items Here') # 给提示文本添加缩进标签 items.tag_add('indent', '1.0', tk.END) items.config(state='disabled',highlightthickness=2,highlightbackground='white',highlightcolor='white') return # 获取条目详情 cur.execute(query.format('Menu' + course)) # 组装并插入菜单内容 items.config(state = 'normal') items.delete(1.0,'end') for i in range(1,n + 1): result = cur.fetchone() items.insert(tk.END,'\n\n' + str(i) + ". " + result[0] + ' (' + str(result[1]) + '$)' + '\n' + result[2]) # 给所有菜单内容添加缩进标签 items.tag_add('indent', '1.0', tk.END) items.config(state='disabled',highlightthickness=2,highlightcolor='white',highlightbackground='white')
方案二:手动给每行开头加双空格
如果不想用标签,也可以直接在插入文本时,给每个新行的开头加上两个空格:
比如循环插入菜单的部分改成:
items.insert(tk.END, '\n\n ' + str(i) + ". " + result[0] + ' (' + str(result[1]) + '$)' + '\n ' + result[2])
空提示的部分改成:
items.insert(tk.END, '\n\n\n\n\n\n\n\n\n\n No Items Here')
这种方法需要确保所有换行后的内容都手动加空格,适合内容结构固定的场景。
内容的提问来源于stack exchange,提问作者Zayan Anwar
相关产品推荐
相关产品推荐

