使用 Python 的 Tkinter,我如何保存数据以仅在该应用程序上使用?

Posted

技术标签:

【中文标题】使用 Python 的 Tkinter,我如何保存数据以仅在该应用程序上使用?【英文标题】:Using Python's Tkinter, how do I save data to use only on that application? 【发布时间】:2016-09-29 01:00:55 【问题描述】:

我只是想制作一个应用程序,我可以在其中创建角色并将它们仅保存到应用程序中。我不知道如何在不将其保存到计算机本身的情况下保存它。主屏幕上有两个选项,一个是创建,另一个是查看配置文件。我不知道如何连接它们。我会把代码放上去,不过为了节省篇幅,只是一小部分。

import tkinter
from tkinter import *

class Application(Tk):
  def __init__(self, *args, **kwargs):
    Tk.__init__(self, *args, **kwargs)

    self.minsize(width=1300, height=750)
    self.maxsize(width=1300, height=750)

    container = Frame(self)
    container.pack(side="top", fill="both", expand=True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)

    #there will be another page for profiles
    self.frames=
    for F in (Startpage, Createpage):
        page_name = F.__name__
        frame = F(parent=container, controller=self)
        self.frames[page_name] = frame

        frame.grid(row=0, column=0, sticky="nsew")

    self.show_frame("Startpage")

def show_frame(self, page_name):
    frame = self.frames[page_name]
    frame.tkraise()


class Startpage(Frame):
 def __init__(self, parent, controller):
    Frame.__init__(self, parent)
    self.controller = controller

    self.configure(bg='white')

    headLabel = Label(self, text="Character Profiles", font=("Times New Roman", 36), bg='white', height=2)
    headLabel.grid(row=0, column=0, columnspan=3, padx=10, pady=25, sticky='n')

    createButton = Button(self, text="Create", font=("Times New Roman", 20), bg="black", fg="white", width=30, height=2,
                        command=lambda: controller.show_frame("Createpage"))
    createButton.grid(row=1, column=2, padx=30, pady=2, sticky="sw")

    profilesButton = Button(self, text="Profiles", font=("Times New Roman", 20), bg="black", fg="white", width=30, height=2)
    profilesButton.grid(row=1, column=0, padx=30, pady=2, sticky="se")

    spacer1 = Label(self, bg='white', width=33)
    spacer1.grid(row=1, column=1, padx=10, pady=20)

class Createpage(Frame):
 def __init__(self, parent, controller):
    Frame.__init__(self, parent)
    self.controller = controller

    self.configure(bg='white')

    backButton = Button(self, text="back", font=("Times New Roman", 20), bg='black', fg='white',
                        command=lambda: controller.show_frame("Startpage"))
    backButton.grid(row=0, column=0, padx=10, pady=2)

    headLabel = Label(self, text="Create a New Character", font=("Times New Roman", 24), bg='white')
    headLabel.grid(row=0, column=4, padx=10, pady=2)

    img = PhotoImage(file="rsz_profilepic.png")

    picLabel = Label(self, image=img, borderwidth=0)
    picLabel.image = img
    picLabel.grid(row=1, column=0, padx=10, pady=2, columnspan=4)


    fullnameLabel = Label(self, bg="white", text="Full Name: ", font=("Times New Roman", 16))
    fullnameLabel.grid(row=2, column=0, padx=0, pady=2, sticky="E")
    #this would be the file name
    fullnameEntry = Entry(self, font=("Times New Roman", 14), bg="#EEEEEE")
    fullnameEntry.grid(row=2, column=1, columnspan=3, padx=0, pady=2, sticky="w")

    nicknameLabel = Label(self, font=("Times New Roman", 16), text="Alias: ", bg="white")
    nicknameLabel.grid(row=3, column=0, padx=0, pady=2)

    aliasEntry = Entry(self, font=("Times New Roman", 16), bg="#EEEEEE")
    aliasEntry.grid(row=3, column=1, columnspan=3, sticky="W")

    sexLabel = Label(self, text="Sex: ", bg="white", font=("Times New Roman", 16))
    sexLabel.grid(row=4, column=0, padx=0, pady=2)

    v = IntVar()
    male = Radiobutton(self, text="Male", bg="white", variable=v, value=1)
    female = Radiobutton(self, text="Female", bg="white", variable=v, value=2)
    other = Radiobutton(self, text="Other", bg="white", variable=v, value=3)
    male.grid(row=4, column=1, sticky="w")
    female.grid(row=4, column=2, sticky="w")
    other.grid(row=4, column=3, sticky="w")

    ageLabel = Label(self, text="Age: ", bg="white", font=("Times New Roman", 14))
    ageLabel.grid(row=5, column=0, padx=0, pady=2)

    ageEntry = Entry(self, font=("Times New Roman", 14), bg="#EEEEEE")
    ageEntry.grid(row=5, column=1, columnspan=3, padx=0, pady=2, sticky="w")

    statusLabel = Label(self, text="Status: ", bg="white", font=("Times New Roman", 14))
    statusLabel.grid(row=6, column=0, padx=0, pady=2)

    s = IntVar()
    alive = Radiobutton(self, text="Alive", bg="white", variable=s, value=1)
    deceased = Radiobutton(self, text="Deseased", bg="white", variable=s, value=2)
    alive.grid(row=6, column=1, sticky="w")
    deceased.grid(row=6, column=2, sticky="w")

    bigassFrame = Frame(self, bg='white', width=1000, height=1000)
    bigassFrame.grid(row=1, column=4, rowspan=50, padx=10, pady=2)

    #there are more buttons below these two
    generalButton = Button(bigassFrame, text="General", font=("Times New Roman", 14), width=25, fg='white', bg='black')
    generalButton.grid(row=0, column=0, padx=10, pady=2)

    appearanceButton = Button(bigassFrame, text="Appearance", font=("Times New Roman", 14), width=25, fg='white', bg='black')
    appearanceButton.grid(row=1, column=0, padx=10, pady=2)

    #here is where the information to be stored is
    genFrame = Frame(self, bg='white')
    genFrame.grid(row=1, column=6, padx=10, pady=2)

    nameLabel = Label(genFrame, text="Name: ", font=("Times New Roman", 14), bg='white')
    nameLabel.grid(row=0, column=0, padx=0, pady=2)
    nameEntry = Entry(genFrame, font=("Times New Roman", 14), bg="#EEEEEE")
    nameEntry.grid(row=0, column=1, padx=0, pady=2)

    namemeaningLabel = Label(genFrame, text="Name Meaning: ", font=("Times New Roman", 14), bg='white')
    namemeaningLabel.grid(row=1, column=0, padx=0, pady=2)
    namemeaningEntry = Entry(genFrame, font=("Times New Roman", 14), bg="#EEEEEE")
    namemeaningEntry.grid(row=1, column=1, padx=0, pady=2)

    q1Label = Label(genFrame, text="Who named him/her?", font=("Times New Roman", 14), bg='white')
    q1Label.grid(row=2, column=0, padx=0, pady=2)
    q1Entry = Entry(genFrame, font=("Times New Roman", 14), bg="#EEEEEE")
    q1Entry.grid(row=2, column=1, padx=0, pady=2)


    #this button will save a copy of the information to the profiles page
    saveButton = Button(self, text="Save", font=("Times New Roman", 14))
    saveButton.grid(row=0, column=7)


if __name__ == "__main__":
 app = Application()
 app.title("Character Profiles")
 app.geometry("1000x800+20+20")
 app.mainloop()

我以前从未在这里发布过问题,所以我不确定我是否做得对。

【问题讨论】:

以后尽量减少代码。这需要仔细研究,尤其是当它与您的问题并不完全相关时。我见过更糟糕的第一个问题。 您是在问如何在关闭和打开应用程序之间在 python 中保存数据? @jcolemang 是的。当你关闭它时,当你打开它时,信息仍然存在 【参考方案1】:

我建议开始的方式是使用文本文件。有一个读写文本文件的教程here。这个想法是以您以后可以阅读的已知格式保存所有数据。最常见的方法是让每个实体(在您的情况下为配置文件)成为文件中的一行,并且实体的每个属性用逗号分隔。我不确切知道您存储的是哪种配置文件,但这是一个通用示例:

要创建配置文件,请将其添加到 profiles.txt 文件的末尾

first_name = 'john'
last_name = 'doe'
favorite_language = 'python'
file = open('profiles.txt', 'a') # 'a' for append. Don't overwrite old content
file.write(first_name + ',' + last_name + ',' + favorite_language)
file.close()

然后,读取所有配置文件:

file = open('profiles.txt', 'r')
lines = file.read_lines()
for line in lines:
    info = line.split(',')
    first_name = info[0]
    last_name = info[1]
    fav_language = info[2]
    # do something with this info
file.close()

您也可以将配置文件存储在对象中,可能是这样的:

class Profile():
    def __init__(self, first_name, last_name, fav_language):
        self.first_name = first_name
        self.last_name = last_name
        self.fav_language = fav_language

    def save(self):
        file = open('profiles.txt', 'a')
        file.write(first_name + ',' + last_name + ',' + favorite_language)
        file.close()

当然,这种方法远非完美。例如,如果用户在他们的名字中输入逗号会发生什么?现在split 要么返回不正确的信息,要么您遇到错误。如果您希望它真正健壮,您必须进行各种字符串处理以使其至少难以破解,或者您不能允许用户在其名称中使用逗号。

最后一点,人们通常在“现实世界”中解决您遇到的问题的方式是使用数据库。如果您有兴趣,请查看 mysql、Postgresql 或 MongoDB 之类的东西。它们比编写文本文件要复杂得多,但效果要好得多。它们本质上是您计算机上的独立程序,专门为您保存和检索数据。

【讨论】:

以上是关于使用 Python 的 Tkinter,我如何保存数据以仅在该应用程序上使用?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 tkinter 按钮在 python 中写入文件?

Python Tkinter - 保存画布 - tkinter 崩溃

如何在 Tkinter 记事本中添加“保存”、“复制”和“粘贴”?

如何拍摄由 Python-tkinter 创建的正在运行的 GUI 窗口的快照并保存为图像文件(.jpeg/.png)?

如何在 python 3.4 tkinter“索引错误:列表索引超出范围”中修复此错误

Python Tkinter 中的单选按钮值