【问题标题】:How to set background in turtle python如何在海龟python中设置背景
【发布时间】:2019-02-26 06:32:03
【问题描述】:

我正在开发一款太空侵略者游戏,但我遇到了一个问题,我的背景无法正常工作。这是他需要但没有工作的代码:

wn = turtle.Screen() 
wn.bgcolor("black")
wn.title("Space Invaders")
wn.bgpic('space_invaders_background.gif')

错误信息说

'[正在运行] python -u "d:\USERS\chedl\Documents\Apps\games_and_apps\offline\python\space_invaders\main.py" 回溯(最近一次通话最后): 文件“d:\USERS\chedl\Documents\Apps\games_and_apps\offline\python\space_invaders\main.py”,第 10 行,在 wn.bgpic('space_invaders_background.gif') 文件“C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\turtle.py”,第 1481 行,在 bgpic self._bgpics[图片名] = self._image(图片名) _image 中的文件“C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\turtle.py”,第 479 行 返回 TK.PhotoImage(file=filename) init 中的文件“C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py”,第 3539 行 Image.init(self, 'photo', name, cnf, master, **kw) init 中的文件“C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py”,第 3495 行 self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError:无法打开“space_invaders_background.gif”:没有这样的文件或目录

[Done] 在 0.273 秒内以 code=1 退出

但 space_invaders_background.gif 与实际的 python 应用程序在同一个文件中。

【问题讨论】:

  • 尝试提供文件的完整路径,看看是否有帮助
  • 我做了,这是我电脑上下载的文件
  • 另外,如果你想要路径,这里是 D:\USERS\chedl\Documents\Apps\games_and_apps\offline\python\space_invaders\space_invaders_background.gif
  • 我不需要这条路径。您应该尝试在代码中使用它。我无法侵入你的目录;)

标签: python python-3.x visual-studio-code turtle-graphics


【解决方案1】:

我将列出更改颜色所需的文档。此外,我看不到您如何拥有一个既是 gif 又是 python 脚本的文件。您是说main.pymy.gif 在同一个目录中吗?如果是这样,请将目录名称列为完整路径。你的操作系统是什么?视窗?那么完整路径是C:\my\path\to\script\my.gif。如果是 Unix,/this/is/a/path/and/dir/my.gif

docs:

turtle.bgcolor(*args)
    Parameters: args – a color string or three numbers in the range 0..colormode or 
    a 3-tuple of such numbers
    Set or return background color of the TurtleScreen.

>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128, 0, 128)

turtle.bgpic(picname=None)
    Parameters: picname – a string, name of a gif-file or "nopic", or None
    Set background image or return name of current backgroundimage. 
    If picname is a filename, set the corresponding image as background. 
    If picname is "nopic", delete background image, if present. 
    If picname is None, return the filename of the current backgroundimage.

>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"

【讨论】:

  • OP 询问最后一行:wn.bgpic('space_invaders_background.gif')
【解决方案2】:

如果您使用的是 Visual Studio Code,请确保重新启动应用程序并选择包含 python 文件的文件夹作为工作区文件夹,如下所示

希望这能解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多