如何将tkinter窗口内的条目打印输出到外部文件?
问题解决方法
问题根因
你当前代码中的rec_content变量在遍历选中条目的循环中被反复赋值覆盖,循环结束后仅保留了最后一条商品的格式化内容,因此写入文件的列表里只有最后一条商品记录,出现导出内容不全的问题。
修改后的代码
get_content = listbox2.get(0, END) # 获取用户选中的条目 bb = Label(receipt_window, text="Bert's Burgers") line1 = Label(receipt_window, text='----------------------------------------------------------------') bb.pack() line1.pack() # 初始化列表保存所有格式化后的条目内容 rec_content_list = [] # 加入和窗口展示一致的抬头、分割线 rec_content_list.append("Bert's Burgers") rec_content_list.append('----------------------------------------------------------------') for con_item in get_content: # 拆分条目为两个变量用于文本格式化 con1, con2 = con_item.split('PHP') rec_content = f'{con1:<30}costs PHP{con2:<8}' receipt = Label(receipt_window, text=rec_content) receipt.pack() # 将当前条目的格式化内容追加到列表 rec_content_list.append(rec_content) # 拼接全部待导出内容 item_list = rec_content_list + [ "Cost" + str(cost), "Cash Paid" + payment.get(), "Change" + str(change_formula) ] with open("receipt.txt", "w", encoding="utf-8") as f: # 指定编码避免乱码 for line in item_list: f.write(line) f.write("\n")
核心改动说明
- 新增列表
rec_content_list存储所有格式化后的商品条目,解决单变量循环覆盖的问题 - 导出内容新增抬头和分割线,和窗口展示效果保持一致
- 写入文件时指定utf-8编码,避免特殊字符乱码
内容的提问来源于stack exchange,提问作者Zven Reyes
相关产品推荐
相关产品推荐

