赋值之前的变量引用Python

时间:2017-08-13 22:58:49

标签: python python-3.x scope python-imaging-library pillow

我在按下TKinter按钮后发生的hangman游戏中为函数编写代码。显然,tempString变量在赋值之前被引用,我对它的原因非常困惑。

程序从txt文件中随机选择一个单词,从中选择一行中的一个元素。

此外,我设置了一个系统来检测输入框中的输入,该输入框检查输入的字符是否在已选择的单词中,大多数控制台命令用于测试游戏。

更新照片功能会更改显示的图像(系列为7,0 =无错误6 =全身绘制。)

from tkinter import *
from PIL import ImageTk, Image
import random

root = Tk()
i=0
failCount = 0
displayString = ""

frameLeft = Frame(root)
frameRight = Frame(root)
frameRight.pack(side=RIGHT)
frameLeft.pack(side=LEFT)

#word List
lineNumbers = 0
wordList = open("wordlist.txt", "r")
lines = wordList.readlines()
print(lines)
randomWord = lines[random.randint(0,len(lines)-1)]
print(len(lines))
print(randomWord)
for a in range(len(randomWord)-1):
        print(a)
        displayString = displayString + "~"
print(displayString)
wordList.close()


#frame Right
img = ImageTk.PhotoImage(Image.open("S" + str(i) + ".gif"))
imgPanel = Label(frameRight, image = img)
imgPanel.pack(side=BOTTOM, fill=BOTH, expand=YES)

#frame Left

#function Declaration
entry1 = Entry(frameLeft)
entry1.pack()
labelInstruction = Label(frameLeft, text="Vape nation")
labelInstruction.pack()
def doGame():
        tempString = ""
        tempString = list(displayString)
        if str.lower(entry1.get()) in randomWord:
                labelInstruction.config(text="Yes")
                charPosition = []
                for n in range(len(randomWord)-1):
                        if randomWord[n] == entry1.get():
                                charPosition.append(n)
                for a in range(len(charPosition)):
                        tempString[charPosition[a]] = entry1.get()
                displayString = "".join(tempString)
                if randomWord == displayString:
                        print("You Win")

        elif len(entry1.get()) != 1:
                labelInstruction.config(text="Entered line is unacceptable single characters only.")
        else:
                global failCount
                labelInstruction.config(text="Incorrect")
                if failCount != 6:
                        failCount +=1
                else:
                        labelInstruction.config(text="Game Over you have failed")
                updatePhoto()
def updatePhoto():
        i = failCount
        img = ImageTk.PhotoImage(Image.open("S" + str(i) + ".gif"))
        imgPanel.configure(image=img)
        imgPanel.image = img
submitButton = Button(frameLeft, text="Submit", command=doGame)
submitButton.pack()


root.mainloop()

0 个答案:

没有答案