Python Tkinter开发报错:TextIOWrapper.write()参数数量不匹配求助
问题排查与解决方案
错误原因
f.write()方法仅支持接收单个字符串参数,你代码中同时传入了输入框对象、换行符等共16个参数,直接触发TypeError报错。Entry(sign).place(xxx)的写法错误,place()方法无返回值,执行后e1到e8变量全部为None,即使修复传参问题也无法拿到用户输入的内容。- 写文件的逻辑直接放在窗口初始化代码后,程序运行时会在窗口弹出的瞬间就执行写文件操作,不会等待用户输入后点击提交按钮触发。
- 字符串形式的Windows文件路径未做转义处理,路径中的特殊字符可能被识别为转义符导致文件打开失败。
修复后的完整代码
import tkinter as tk from tkinter import * def sign_in(): sign = tk.Tk() sign.title("Learn English To Study Abroad - LETSA | v0.0.1") sign.geometry("300x210") Label(sign, text = "Your Account: ").place(x = 0, y = 0) Label(sign, text = "Your Fullname: ").place(x = 0, y = 20) Label(sign, text = "Your age: ").place(x = 0, y = 40) Label(sign, text = "Your birthday: ").place(x = 0, y = 60) Label(sign, text = "Your Email address: ").place(x = 0, y = 80) Label(sign, text = "Your Phone number (Optional): ").place(x = 0, y = 100) Label(sign, text = "Your Password: ").place(x = 0, y = 120) Label(sign, text = "Re-Your password: ").place(x = 0, y = 140) # 先创建Entry对象,再调用place方法,保证变量存储的是输入框实例 e1 = Entry(sign) e1.place(x = 85, y = 0) e2 = Entry(sign) e2.place(x = 90, y = 20) e3 = Entry(sign) e3.place(x = 60, y = 40) e4 = Entry(sign) e4.place(x = 80, y = 60) e5 = Entry(sign) e5.place(x = 110, y = 80) e6 = Entry(sign) e6.place(x = 175, y = 100) e7 = Entry(sign) e7.place(x = 90, y = 120) e8 = Entry(sign) e8.place(x = 110, y = 140) # 封装写文件逻辑,绑定给提交按钮 def save_data(): # 读取所有输入框内容,拼接为单个字符串 content = '\n'.join([ e1.get(), e2.get(), e3.get(), e4.get(), e5.get(), e6.get(), e7.get(), e8.get() ]) + '\n' # 路径加r前缀标记为原始字符串,避免转义问题 with open(r'D:\VS Code\Bài code cuối khóa\info1.txt', 'a', encoding='utf-8') as f: f.write(content) btn_sumbit = tk.Button( sign, bg="light blue", fg="green", activeforeground = "red", activebackground = "light green", text = "Sign in!", width = 20, height = 2, command=save_data # 绑定写文件触发逻辑 ) btn_sumbit.pack(side = BOTTOM) sign.mainloop() # 调用函数启动注册窗口 sign_in()
内容的提问来源于stack exchange,提问作者Study Code
相关产品推荐
相关产品推荐

