赋值前的变量引用

2024-06-10 01:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个函数的代码,在一个刽子手游戏,发生在一个TKinter按钮被按下。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()

Tags: textinimglenrootpacklinesprint