Python TKinter将数据保存在csv文件中

lnlaulya  于 2022-10-22  发布在  Python
关注(0)|答案(1)|浏览(242)

我已经在StackOverflow上搜索了类似问题的答案,但我找不到适合我的案例的答案…我的脚本总是返回此错误:

Avvio: python3 /...my_script.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib64/python3.10/tkinter/__init__.py", line 1921, in __call__
    return self.func(*args)
  File "/...my_script.py", line 243, in <lambda>
    command=lambda:save_sheet(nam, srn, brt)
TypeError: make_sheet.<locals>.save_sheet() takes 0 positional arguments but 3 were given

此代码:

from tkinter import *
from tkinter import ttk
import csv

def make_sheet():
    win = Tk()
    frm_win = Frame(win)
    frm_win.pack()

    surn = StringVar()
    nam = StringVar()
    brt = StringVar()

    def save_sheet():
        a_surname = surn.get()
        a_name = nam.get()
        a_birth = brt.get()

   Label(frm_win, text="Surname ", font=14).grid(row=0, column=0, ipady=3, sticky ='e')
   Entry(frm_win, textvariable=surn, width=30, justify=CENTER).grid(row=0, column=1, sticky ='w')

   Label(frm_win, text="Name ", font=14).grid(row=1, column=0, ipady=3, sticky ='e')
   Entry(frm_win, textvariable=nam, width=30, justify=CENTER).grid(row=1, column=1, sticky ='w')

   Label(frm_win, text="Date of birth ", font=14).grid(row=2, column=0, ipady=3, sticky ='e')
   Entry(frm_win, textvariable=brt, width=18, justify=CENTER).grid(row=2, column=1, sticky ='w')

   btn_send = ttk.Button(frm_win, text="Send", width=12, command=lambda:save_sheet(surn, nam, brt))
   btn_send.grid(row=14, column=1, sticky='w', ipady=5, pady=35)

   with open('/home/...my_script.csv', 'a') as doc_csv:
       writer_csv = csv.writer(doc_csv)
       writer_csv.writerow([a_surname, a_name, a_birth])
   doc_csv.close()

   win.mainloop()

那么,为什么我不能将数据保存在.csv文件中?我尝试了很多“组合”,从上到下颠倒部分代码,缩进和取消标识,但任何尝试都无效。我看了一个视频教程,但我真的无法理解我在哪里犯了错误。
提前谢谢。

9fkzdhlc

9fkzdhlc1#

你的代码仍然不会像这样运行。但您可以通过在main方法中像这样初始化StringVar来解决问题

surn = StringVar()
nam = StringVar()
brt = StringVar()

然后使用lambda函数调用save_sheet来传递参数

btn_send = ttk.Button(frm_win, text="Send", width=12, command=lambda : save_sheet(surn, nam, brt))

如果您需要更多信息,可以查看此link以了解一些示例。

相关问题