这是我制作的代码:它会说这是JS但它的Python
from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Mr. Stick Man Races for the Exit")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.canvas_height = 500
self.canvas_width = 500
self.bg = PhotoImage(file = "background.gif")
w = self.bg.width()
h = self.bg.height()
for x in range(0, 5):
for y in range(0, 5):
self.canvas.create_image(x * w, y * h, image=self.bg, anchor='nw')
self.sprites = []
self.running = True
def mainloop(self):
while 1:
if self.running == True:
for sprite in self.sprites:
sprite.move()
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
g = Game()
g.mainloop()
我得到的错误是:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\stickfiguregame.py", line 34, in <module>
g = Game()
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\stickfiguregame.py", line 16, in __init__
self.bg = PhotoImage(file = "background.gif")
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3539, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3495, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "background.gif": no such file or directory
我有一张名为background的图片文件,它是.gif文件。 为什么不起作用? 仅供参考我使用的是Python 3.6.1
答案 0 :(得分:0)
您的脚本无法找到图片文件。尝试使用完整路径替换"background.gif"
,或将其复制到与脚本相同的目录中。
答案 1 :(得分:-1)
将这些导入放在最上面:
from PIL import Image
import ImageTk
并替换它:
self.bg = PhotoImage(file = "background.gif")
用这个:
self.bg = ImageTk.PhotoImage(Image.open('background.gif'))
如果不起作用,请尝试:
self.bg = PhotoImage(Image.open('background.gif'))