我在这里四处寻找解决方案,尽管它们似乎符合我的需求,但最终对我不起作用。我不是特别确定为什么。我将尝试说明问题是什么,希望您能够说明为什么会有所不同。
所以,我一直在尝试使用 Tkinter GUI 制作一个简单的用户名和密码登录系统。我已经尝试通过将用户名和密码放在外部 CSV 文件中,然后让我的程序来完成这项工作,一旦我的游戏的两个用户都已经在尝试登录,逐行读取我的 csv 文件(称为“Accepted Users for Card Game.csv”),它与程序位于同一文件夹中,因此不需要其他目录。我已经尝试让用户将他们的用户名和密码放入不同的 Tkinter 条目中,然后按下它下面的按钮。然后程序会检查,例如,line[0] == PlayerOneUsername and line[1] == PlayerOnePassword
,但是每次我尝试这样做时,它都不起作用。(我的分隔符是 ',',对于任何想知道的人)。
在让它打印正在阅读的内容后,我发现它总是返回行的第一个字符而不是第一个单词,所以当然它一直不正确。我一直在寻找答案,其中一些我已经在尝试,但是每次我尝试实现它时,似乎都在发生同样的问题。(EG line.split() 没有解决我的问题)。
这是比较 line 和 line[0] 彼此相邻的输出。(之后忽略颜色和标题,这些与游戏有关)。
这是当您按下按钮时触发的我的播放器 2 评估的部分(它或多或少与我的播放器 1 评估相同):
Success["text"] = ""
if not PasswordLoginInputTwo.get() or not UsernameLoginInputTwo.get():
Success["text"] = "One or more of your password/username entries are empty. Please try again."
else:
csvfile = open ("Accepted Users for Card Game.csv", "r")
Csvreader = csv.reader(csvfile, delimiter = ',')
Success["text"] = "Player Two password/username combination has been read."
for line in csvfile:
print(line[0])
if line:
print(line)
print(line[0])
if line.split(None, 1)[0] == UsernameLoginInputTwo.get() and line.split(None, 1)[1] == PasswordLoginInputTwo.get():
PlayerTwoSuccess = True
PlayerTwoUsername = UsernameLoginInputTwo.get()
PlayerTwoColour = line[2]
PlayerTwoAntithesis = line[3]
PlayerTwoVictorSound = "Victory - "+line[4]+".wav"
PlayerTwoAttempts = PlayerTwoAttempts + 1
外部 csv 文件只是以简单的行格式排列,如下所示:
PlayerOne,Password1,Purple,Yellow,Donkey Kong
PlayerTwo,Password2,Red,Green,Final Fantasy
PlayerThree,Password3,Pink,Purple,Worms
PlayerFour,Password4,Black,White,Team Fortress 2
我知道答案可能很明显,但我很恼火我似乎找不到答案!顺便说一下,我正在使用 Python 2.7,但我不打算继续使用它。(正如您可能会说的,我对 Python 非常陌生,所以请解释任何解决方案,就像我非常愚蠢一样 - 尽管您可能已经从我的代码和整体问题中得到了这种印象,哈哈)。谢谢!
所以基本上,重复一遍,我的印象是 line[0] 应该是我的“line”中的第一个“word”,在这种情况下是“PlayerOne”。相反,它给了我第一个字符,在本例中为“P”。我该如何解决这个问题?这是什么原因造成的?我怎样才能使它成为第一个单词而不是第一个字符?谢谢!
您正在迭代:
for line in csvfile:
这将返回一个表示第一行的字符串。您需要遍历 reader 对象:
for line in Csvreader:
然后, line 将是在分隔符上拆分的字符串的元组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句