简体   繁体   English

将多个用户输入添加到字典中并将其写入到CSV,Python Tkinter中

[英]Adding multiple user inputs to a dictionary and writing them to csv, python tkinter

First post on here! 在这里的第一篇文章! I am currently learning python mainly with tkinter to make a GUI that will accept user inputs and save them to a csv. 我目前主要通过tkinter学习python,以制作一个可以接受用户输入并将其保存到csv的GUI。

I have it taking and saving user inputs but i think it would be more benifical to save all the inputs to a dictionary and then call the whole dictionary to be saved to csv. 我有它采取并保存用户输入,但我认为将所有输入保存到字典中,然后调用整个字典以保存到csv更为有益。 So far i have this, i dont like the way i'm conintually writing to the csv one after each other. 到目前为止,我有这个,我不喜欢我一个接一个地连续写到csv的方式。 I'd rather call the whole dictionary. 我宁愿叫整个字典。 I had thought something like 我曾经想过

inputs = {'name':'self.input1.get()', 'age':, 'self.input2.get()'}

doesn't seem to be working though? 似乎没有工作吗? Code is below thanks! 代码在下面,谢谢!

from tkinter import * 
import csv

class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.output()

    def output(self):
        Label(text='Name:').grid(row=0, column=0, padx=5,pady=5)
        self.input1 = Entry(root, width=10)
        self.input1.grid(row=0, column=1,padx=5,pady=5)

        Label(text='Age:').grid(row=1, column=0,padx=5,pady=5)
        self.input2 = Entry(root, width=10)
        self.input2.grid(row=1, column=1,padx=5,pady=5)      


        self.b = Button(root, text='Submit', command=self.writeToFile)
        self.b.grid(row=4, column=4,padx=5,pady=5)



    def writeToFile(self):
        with open('WorkOrderLog.csv', 'w') as f:
            w=csv.writer(f, quoting=csv.QUOTE_ALL)
            w.writerow([self.input1.get()])
            w.writerow([self.input2.get()])

if __name__ == "__main__":
    root=Tk()
    root.title('Auto Logger')
    root.geometry('1000x100')
    app=App(master=root)
    app.mainloop()
    root.mainloop()

You will need separate the submission and write processes into their own functions. 您将需要将提交过程和编写过程分成各自的功能。 I would suggest creating an array that you append dictionaries to. 我建议创建一个附加字典的数组。 For example 例如

self.data = [
    {'name': 'John', 'age':23},
    {'name': 'Sally', 'age':26},
]

Then when it comes time to write your data to a file, you can iterate over your list to write each line of the csv. 然后,当需要将数据写入文件时,可以遍历列表以写入csv的每一行。

You can create an initially empty array like self.data = [] and then add to it with something like self.data.append({'name': self.input1.get(), 'age': self.input2.get()}) . 您可以创建一个初始为空的数组,例如self.data = [] ,然后使用self.data.append({'name': self.input1.get(), 'age': self.input2.get()}) When it comes time to write it to a csv, you can iterate over it. 当需要将其写入csv时,可以对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM