gpt4 book ai didi

python - 在 Python 上显示背景时出现问题。 Canvas

转载 作者:太空宇宙 更新时间:2023-11-04 05:00:53 25 4
gpt4 key购买 nike

from tkinter import *

WIDTH = 800
HEIGHT = 950
RAD = 20
SPEED = 30

class mainHero():
def __init__(self):
self.image = PhotoImage(file="darth_vader.png")
self.imageSize = [112,180]
self.right_side = WIDTH/2+self.imageSize[0]/2
self.left_side = WIDTH/2-self.imageSize[0]/2
self.obj = canv.create_image((WIDTH/2,HEIGHT-self.imageSize[0]/2), image = self.image)
def move(self, event):
if event.keysym == "Right":
if self.right_side+SPEED<WIDTH:
canv.move(self.obj, SPEED, 0)
self.right_side += SPEED
self.left_side += SPEED
if event.keysym == "Left":
if self.left_side-SPEED>0:
canv.move(self.obj, -SPEED, 0)
self.right_side -= SPEED
self.left_side -= SPEED
print(self.left_side, self.right_side)

root = Tk()
root.title("YeGame")
root.minsize(width = WIDTH, height = HEIGHT)
root.maxsize(width = WIDTH, height = HEIGHT)
canv = Canvas(root,width =WIDTH,height = HEIGHT, bg="green")
canv.create_rectangle(0, 0, WIDTH%SPEED-1, HEIGHT, fill = "yellow")
canv.create_rectangle(WIDTH-WIDTH%SPEED+1, 0, WIDTH, HEIGHT, fill = "yellow")
m = canv.create_image((100,100), image = PhotoImage(file="smallnight.gif"))
canv.pack()
canv.focus_set()
me = mainHero()
canv.bind("<KeyPress>", me.move)
root.mainloop()

这段代码应该创建游戏。但是我不明白为什么我可以在 Canvas 上看到 Darth Vader 但看不到 Canvas 的背景。它应该是空间的图像。添加 Darth Vader 的代码有效,但添加背景的代码无效。请告诉我如何以正确的方式做到这一点。 Photo

最佳答案

应该在调用 create_image 之前声明图像,就像您在上面为维德先生所做的那样:

root = Tk()
root.title("YeGame")
root.minsize(width = WIDTH, height = HEIGHT)
root.maxsize(width = WIDTH, height = HEIGHT)
canv = Canvas(root,width =WIDTH,height = HEIGHT, bg="green")
canv.create_rectangle(0, 0, WIDTH%SPEED-1, HEIGHT, fill = "yellow")
canv.create_rectangle(WIDTH-WIDTH%SPEED+1, 0, WIDTH, HEIGHT, fill = "yellow")
background = PhotoImage(file="smallnight.gif")
m = canv.create_image((100,100), image = background)
canv.pack()
canv.focus_set()
me = mainHero()
canv.bind("<KeyPress>", me.move)
root.mainloop()

关于python - 在 Python 上显示背景时出现问题。 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com