因此我们创建了一个基于文本的冒险游戏的团队项目,并且必须在游戏中加入GUI。虽然GUI和TBA工作正常,但我很难将两者结合起来。我需要用户在Entry Box中输入命令,并根据输入有GUI打印出现有功能中的文本。我正在使用tkinter进行GUI。任何帮助将不胜感激!
基于文本的冒险的一部分
def initWorldVals():
worldVals = [1,0,0,0,0,0,0,'Start Room']
global worldVals
## Room class
class Room:
def __init__(self,x,y,name,desc,memo):
self.x = x
self.y = y
self.name = name
self.desc = desc
self.memo = memo
def getX(self):
return self.x
def getY(self):
return self.y
def getName(self):
return self.name
def getDesc(self):
return self.desc
def getMemo(self):
return self.memo
numOfRooms = len(roomList)
for i in range(numOfRooms):
roomList[i] = Room(rooms[i*3],rooms[(i*3)+1],
rooms[(i*3)+2],desc[(i*2)+1],memo[i])
## Main program functions
# Room movement
def actionRoom(x,y,commLine,roomList,actionType):
if commLine == "NORTH":
y += 1
if actionType == 'GO':
for i in range(numOfRooms):
if roomList[i].getX() == x and roomList[i].getY() == y:
worldVals[7] = roomList[i].getName()
worldVals[6] = roomList[i].getY()
if worldVals[5] != x or worldVals[6] != y:
errorComm(commLine,'GO')
elif actionType == 'LOOK':
for i in range(numOfRooms):
if roomList[i].getX() == x and roomList[i].getY() == y:
print(roomList[i].getMemo())
lookRoomNum = i
return lookRoomNum
if roomList[lookRoomNum] != x or roomList[lookRoomNum] != y:
errorComm(commLine,'LOOK')
elif commLine == "SOUTH":
y -= 1
if actionType == 'GO':
for i in range(numOfRooms):
if roomList[i].getX() == x and roomList[i].getY() == y:
if roomList[i] == roomList[5] and worldVals[1] == 0:
print("Without looking, you step into the room "
"blindly, and fall into a large pit in the "
"center of the room. The fall is too great, "
"and you do not survive the fall.\n\n")
worldVals[0] = -1
worldVals[7] = roomList[i].getName()
worldVals[6] = roomList[i].getY()
if worldVals[5] != x or worldVals[6] != y:
errorComm(commLine,'GO')
elif actionType == 'LOOK':
for i in range(numOfRooms):
if roomList[i].getX() == x and roomList[i].getY() == y:
if roomList[i] == roomList[5]:
worldVals[1] = 1
print(roomList[i].getMemo())
lookRoomNum = i
return lookRoomNum
if roomList[lookRoomNum] != x or roomList[lookRoomNum] != y:
errorComm(commLine,'LOOK')
GUI代码:
from tkinter import *
import sys
class Display(Frame):
mGui = Tk()
mGui.geometry("500x500-500-300") #Size of Widget
mGui.title("Text Based Adventure!")
mlabel = Label(mGui,text = "Welcome adventurer where do you wish to go").pack()
def __init__(self):
Frame.__init__(self)
self.entry = Entry(self) #Entry textbox
self.entry.pack()
self.entry.bind("<Return>", self.onEnter)
self.clearButton = Button(self, text="Clear text", command=self.clear_text) #Clear text button
self.clearButton.pack()
self.output = Text(self) #Textbox
self.output.pack()
sys.stdout = self
self.pack()
def onEnter(self,Frame):
print(self.entry.get()) #Waits for enter to display text
def write(self, txt):
self.output.insert(END,str(txt)) #displays text
def clear_text(self):
self.entry.delete(0, "end") #Clears text
if __name__ == '__main__':
Display().mainloop()