[英]Python tkinter image not displaying
so i am trying to make a 2d "minecraft" game in python, but i just cant get an image to show up所以我想在 python 中制作一个 2d“我的世界”游戏,但我只是无法显示图像
I have this code now:我现在有这个代码:
from tkinter import *
import time
class Block:
def __init__(self, posx, posy, game):
self.x = posx
self.y = posy
self.game = game
self.grass_block = PhotoImage(file="grass_block.gif")
print("place")
self.image = self.game.canvas.create_image(posx, posy, image=self.grass_block, anchor="nw")
self.hoi = self.game.canvas.create_oval(100,100,100,100, fill = "red")
def get_image(self):
return self.image
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("MijnCraft")
self.tk.resizable(0, 0)
self.canvas = Canvas(self.tk, width=1000, height=1000, highlightthickness=0)
self.canvas.pack()
self.bg = PhotoImage(file="nacht.gif")
self.canvas.create_image(0, 0, image=self.bg, anchor="nw")
self.aan = True
self.genworld()
def genworld(self):
print("make")
Block(100, 100, self)
def gameloop(self):
while self.aan:
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
spel = Game()
spel.gameloop()
But i just cant get a block image to show up, i just get the backgound, does someone know what i am doing wrong, (i dont get any errors)(it does print the 2 debug messages) i hope you can help!但我只是无法显示块图像,我只是得到背景,有人知道我做错了什么吗,(我没有收到任何错误)(它确实打印了 2 条调试消息)我希望你能帮忙!
Your instance of Block
is a local object that is getting destroyed when genworld
returns.您的
Block
实例是本地 object ,它在genworld
返回时被销毁。 To prevent this, save a reference to the block.为防止这种情况,请保存对块的引用。 Assuming you're going to want to create more than one block, you can use a list or dictionary.
假设您要创建多个块,您可以使用列表或字典。
class Game:
def __init__(self):
self.blocks = []
...
def genworld(self):
self.blocks.append(Block(100, 100, self))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.