0
我的目標是每次用戶按下shift按鈕時加載一個新的「箭頭」圖像。我想,我可以爲箭頭創建一個類,以便爲每個實例創建一個新的實例,其中每個實例都有自己的座標,等等。但顯然我做錯了。我試圖爲實例創建一個列表,以便我可以迭代它,然後在每個實例中使用moveArrow方法。我剛剛獲得了5個參賽項目,因爲我想要限制5個箭頭。我希望這段代碼不會給你眼睛或類似的東西:P我是一個新手,我很抱歉,如果代碼非常糟糕或者如何處理我的問題的方法。謝謝你的幫助:)用Tkinter正確地實例化課程
#!/usr/bin/python
from Tkinter import *
from PIL import ImageTk, Image
class frameApp(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, height = 400, width = 400)
self.charImg = ImageTk.PhotoImage(Image.open("Archer.gif"))
self.arrowImage = ImageTk.PhotoImage(Image.open("arrow.gif"))
self.charLabel = Label(self, image = self.charImg) #Loading character label
self.charLabel.pack()
self.arrow = Label(self, image = self.arrowImage)
self.arrow.pack()
self.shift = False
self.down = False
self.right = False
self.left = False
self.up = False
self.x_coord = 200
self.y_coord = 200
self.pack_propagate(0)
self.pack()
self.arrowList = ["Inst1", "Inst2", "Inst3", "Inst4", "Inst5"]
self.counter = -1
def moveableImage(self):
self.charLabel.place(y=self.y_coord, x=self.x_coord)
def createArrow(self):
self.arrowList[counter] = arrow()
def moveArrow(self):
for arrowList in self.arrowList:
arrowList.moveArrow
def keyPressed(self, event):
if event.keysym == 'Down':
self.down = True
elif event.keysym == 'Right':
self.right = True
elif event.keysym == 'Left':
self.left = True
elif event.keysym == 'Up':
self.up = True
elif event.keysym == 'Shift_L':
self.shift = True
def keyReleased(self, event):
if event.keysym == 'Down':
self.down = False
elif event.keysym == 'Right':
self.right = False
elif event.keysym == 'Left':
self.left = False
elif event.keysym == 'Up':
self.up = False
elif event.keysym == 'Shift_L':
self.shift = False
def task(self):
if self.down and self.y_coord < 360:
self.y_coord = self.y_coord + 10
elif self.right and self.x_coord < 370:
self.x_coord = self.x_coord + 10
elif self.left and self.x_coord > 10:
self.x_coord = self.x_coord - 10
elif self.up and self.y_coord > 10:
self.y_coord = self.y_coord - 10
elif self.shift:
self.counter += 1
self.createArrow()
root.after(20,self.task)
root.after(20,self.moveArrow)
self.moveableImage()
class arrow(object):
def __init__(self):
self.x_coordArrow = app.x_coord
self.y_coordArrow = app.y_coord
def moveArrow(self):
self.x_coordArrow = self.x_coordArrow + 20
root = Tk()
root.title("Frametitel")
app = frameApp(master=root)
root.bind_all('<Key>', app.keyPressed)
root.bind_all('<KeyRelease>', app.keyReleased)
root.after(20, app.task)
app.mainloop()
我能問你對你的代碼的一個問題? –
當然。它是什麼? – atlasologist
爲什麼你的moveArrow方法不會發出最大的遞歸錯誤?您在moveArrow()方法內調用self.moveArrow(箭頭,xCoord + 15,yCoord)。難道你不應該在任何階段有無休止的遞歸嗎? –