0

I have a statement inside a while statement that is supposed to draw an image onto the canvas but it doesn't happen and I don't know why as it doesn't show any errors.

def buttonclick_gamescreen(event):
    global scorecounter
    global pressed
    global randomimage
    global images
    pressed = ""

    if event.x >853 and event.x <957 and event.y > 8 and event.y < 56 : pressed = 7 
    if event.x >666 and event.x <947 and event.y > 491 and event.y < 534 : pressed = 8
    while pressed == 8 :
        entryx = e1.get()
        entryy = e2.get()
        answerx = answerlistx[randomimage]
        answery = answerlisty[randomimage]
        print("The answer to X is", answerx, "You entered", entryx,"The answer to Y is", answery, "You entered ", entryy)
        if entryx == answerx and entryy == answery:
            print("correct")
            canvas.delete(images)
            randomimage = random.randrange(0,49+1)
            scorecounter = scorecounter + 1
            print("You score is now", scorecounter, "New random number is", randomimage)
            game = PhotoImage(file=imagelist[randomimage])
            images = canvas.create_image(30, 65, image = game, anchor = NW)
            e1.delete(0, END)   
            e2.delete(0, END)
            pressed = ''
        else:
            print("incorrect")
            e1.delete(0, END)   
            e2.delete(0, END)
            pressed = ''

The line images = canvas.create_image(30, 65, image = game, anchor = NW) should work as it worked in another case for me.

Here's a link to the rest of the code since I don't want to make this question too long and messy, which shows where the canvas is drawn. http://pastebin.com/RxmPDUAD From my understanding right now I'll have to create a class and call the functions from there for this to work? EDIT: Having trouble still as I've tried using global variables and classes with no luck.

It's not a problem with the random number as I printed it just before the line the image is supposed to print from just incase it didn't work but it does. What am I doing wrong?

4

1 回答 1

3

在没有实际测试您的代码的情况下,我很确定问题是PhotoImage当您退出该方法时您的对象正在被垃圾收集。出于某种奇怪的原因,只是将它们传递给canvas.create_image不会阻止这种情况。尝试制作它们global

global game
game = PhotoImage(file=imagelist[randomimage])
images = canvas.create_image(30, 65, image = game, anchor = NW)

另请参阅thisthisthis相关问题/答案。

更多指针:

  • 像这样的条件event.x >853 and event.x <957可以写成853 < event.x < 957
  • 你可以定义你imagelist["%d.gif" % (i+1) for i in range(50)]
  • after方法需要以毫秒为单位的时间,所以我想这应该是after(1000, ...)
  • 在当前状态下,while pressed == 8:循环似乎没有多大意义,因为无论如何pressed都设置为经过一次迭代''
  • 最后,我建议定义一个自定义class GameFrame(Frame)并将所有这些东西放在那个类中,而不是制作所有东西global;在这种情况下,您可以使用self关键字将您绑定PhotoImageFrame以防止它被垃圾收集
于 2013-07-21T09:43:00.230 回答