Python - 运行时将数据写入文件时的问题

时间:2015-07-08 19:04:50

标签: python data-storage

我是Python的新手并创建了一个GUI注册系统,我正在创建一个小项目作为项目的一部分。将playername +数据作为小字符串存储到文本文档时,我遇到了一些问题,这是我不确定的问题,以及我无法解决的问题:

  • 记事本文档是以已注册的用户的名义创建的,但是需要输入的数据不是,并且文档留空。
  • 虽然在写入文件时包含if和else语句,但仍会显示错误窗口,该错误窗口应仅在文本文件已存在时显示。

感谢你们给予的帮助,我真的很感激,祝你有个美好的一天! - 果酱

代码:

__author__ = 'Jamie'

# Imports all from Tkinter and imports os.path
from tkinter import *
import os.path
import tkinter.messagebox


# Creates module to run the game
def runGame():
    from pythonDocs import mainGame
    mainGame()


def Details():
    # Creates window
    startGUI = Tk()
    startGUI.geometry("270x250")
    startGUI.title("Python Challenge")

    # Creates text for startScreen
    Label(startGUI, text="Please enter your details:").grid(row=0)
    Label(startGUI, text="Please enter your Username (e.g. Jam40e)").grid(row=2)
    Label(startGUI, text="Please enter your Email (e.g. help@support.com)").grid(row=4)
    Label(startGUI, text="Please enter your Age (In numbers)").grid(row=6)
    Label(startGUI, text="Please enter your Gender (Male or Female)").grid(row=8)

    # Setting global variables
    global e1
    global e2
    global e3
    global e4


    # Creates entry field for details
    e1= Entry(startGUI)
    e1.grid(row=3, column=0)
    e1.focus_set()

    e2 = Entry(startGUI)
    e2.grid(row=5, column=0)
    e2.focus_set()

    e3 = Entry(startGUI)
    e3.grid(row=7, column=0)
    e3.focus_set()

    e4 = Entry(startGUI)
    e4.grid(row=9, column=0)
    e4.focus_set()

    def printtext():
        string = e1.get()
        string1 = e2.get()
        string2 = e3.get()
        string3 = e4.get()

        # Creates filePath
        PATH='./playerdata/' + string + '.txt'

        # Opens some text files to be writen on
        text_file_exists = open ('./playerdata/' + string + '.txt ' , 'w')
        text_file = open ('./playerdata/' + string + '.txt ' , 'w')
        if os.path.exists (PATH):
            tkinter.messagebox.showinfo('ERROR!','This username is already in use!')
        else:
            text_file.write (string + ', ADDSCORE')
            text_file.close()
    # Create entry button
    startButton3 = Button(text="Enter!", width=10, fg = 'green', activeforeground ='red', command = lambda: printtext())
    startButton3.grid(row=11, column=0)

 # Waits for input and draws window
    startGUI.mainloop()

Details()

粘贴到pastebin:http://pastebin.com/8gXc6L1x

1 个答案:

答案 0 :(得分:0)

感谢@NightShadeQueen我意识到我尝试创建文档,然后检查它是否存在,傻我!谢谢你的回答。