我无法启动我的 Python 程序。我遇到了无法打开 .gif 文件的问题,而且我不知道如何打开!
我不断收到一条很长的错误消息:
"RuntimeError: Too early to create image"
我已将 gif 文件移动到与代码相同的项目文件中,我尝试在线查找,但每个人都使用不同的包,我就是找不到解决办法。我也在 pycharm 上打开了 gif。
这是我的代码:
import random
from tkinter import *
sign = random.randint(0, 1)
if (sign == 1):
photo = PhotoImage(file="X.gif")
else:
photo = PhotoImage(file="O.gif")
我的总体目标是展示一张像完成的井字游戏一样的图片,X 和 O 随机放置,并且不必像连续 3 个那样有任何特定的顺序。这是家庭作业问题:
Display a frame that contains nine labels. A label may display an image icon for X or an image icon for O, as shown in Figure 12.27c. What to display is randomly decided.
Use the
Math.random()method to generate an integer 0 or 1, which corresponds to displaying an X or O image icon. These images are in the files x.gif and o.gif.
请您参考如下方法:
我可以从代码中看出,在创建主窗口之前您正在使用 PhotoImage 给您一个运行时错误,错误中明确指出 "Too early to create image" 表示如果没有事件的 Tk 窗口则无法创建图像。
有些人之所以喜欢使用其他模块,是因为它可以让您更灵活地调整大小、 reshape 形状、反转等。 (顺便说一句,它可以 Pillow 模块 from PIL import Image, ImageTk How to use PIL in Tkinter)。
现在回到您的代码。
- 您甚至可以不使用
if-else来随机化“O”和“X”图像。 - 我在创建图像之前创建了主窗口。
- 确保您使用的图像位于同一目录中。
import random
from tkinter import *
sign = random.choice( ["X.gif", "O.gif"] )
print(sign,"photo has been selected")
root = Tk()
Photo = PhotoImage(file=sign)
display_photo = Label(root, image=Photo)
display_photo.pack()
mainloop()
