繁体   English   中英

Python-图片未在画布上绘制

[英]Python - Image not being drawn on canvas

我在while语句中有一个语句,该语句应该将图像绘制到画布上,但不会发生,我也不知道为什么,因为它没有显示任何错误。

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 = ''

images = canvas.create_image(30, 65, image = game, anchor = NW)images = canvas.create_image(30, 65, image = game, anchor = NW)应该可以工作,因为它对我来说是另一种情况。

这是指向其余代码的链接,因为我不想让这个问题太长且混乱,它显示了画布的绘制位置。 http://pastebin.com/RxmPDUAD根据我现在的理解,我将不得不创建一个类并从那里调用函数才能正常工作? 编辑:仍然有麻烦,因为我尝试使用全局变量和类没有运气。

这不是随机数的问题,因为我只是在图像应该打印的行之前打印它,以防万一它不起作用但它确实起作用。 我究竟做错了什么?

在没有实际测试您的代码的情况下,我可以肯定的问题是退出该方法时,正在对您的PhotoImage对象进行垃圾回收。 出于某些奇怪的原因,仅将它们传递给canvas.create_image并不能阻止这种情况。 尝试使其global

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

另请参阅thisthis以及与相关的问题/答案。

一些更多的指针:

  • 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关键字将PhotoImage绑定到Frame以防止被垃圾回收

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM