且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python - 图像不是在画布上绘制的

更新时间:2023-11-24 10:49:10

如果没有实际测试过代码,我很确定问题是你的 PhotoImage 对象被垃圾收集。出于某种奇怪的原因,只需将它们传递给 canvas.create_image 就不会阻止这种情况。尝试让它们全球

Without having actually tested your code, I'm pretty sure the problem is that your PhotoImage objects are being garbage-collected when you exit the method. For some weird reason, just passing them to canvas.create_image won't prevent this. Try to make them global:

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

另见,这个和相关问题/答案。

Also see this, this and this related questions/answers.

更多指示:


  • 条件如 event.x> 853和event.x< 957 可以写成 853< event.x< 957

  • 您可以将 imagelist 定义为 [%d.gif %(i + 1)for i in range(50)]

  • 方法后的一个以毫秒为单位的时间,所以我想这应该是之后(1000,...)

  • 在它的当前状态,按下时== 8:循环似乎没有多大意义,因为按下设置为

  • 最后,我建议定义一个自定义的类GameFrame(Frame)并将所有这些内容放在该课程中,而不是将所有内容全局;在这种情况下,您可以使用 self 关键字将 PhotoImage 绑定到 Frame 以防止垃圾收集

  • conditions like event.x >853 and event.x <957 can be written as 853 < event.x < 957
  • you can define your imagelist as ["%d.gif" % (i+1) for i in range(50)]
  • the after method takes a time in milliseconds, so I guess this should be after(1000, ...)
  • in it's current state, the while pressed == 8: loop seems not to make much sense, since pressed is set to '' after one iteration anyway
  • finally, I'd recommend defining a custom class GameFrame(Frame) and putting all this stuff in that class, instead of making everything global; in this case, you can use the self keyword to bind your PhotoImage to the Frame to prevent it from being garbage-collected