简体   繁体   中英

How do I open .gif file using tkinter without getting error "Too early to create image"?

I cannot start my Python program. I've a problem that I cannot open a .gif file, and I cannot figure out how!

I keep getting a long error message:

"RuntimeError: Too early to create image"

I have moved the gif files into the same project file as the code, and I tried looking online, but everyone uses different packages, and I just cannot find a way around it. I also have the gifs open on pycharm.

Here is my code:

import random
from tkinter import *


sign = random.randint(0, 1)

if (sign == 1):
   photo = PhotoImage(file="X.gif")
else:
    photo = PhotoImage(file="O.gif")

My overall goal is to show an image like a finished tic tac toe game, with randomly placed X's and O's, and there does not have to be any specific order like 3 in a row. Here is the homework problem:

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.

I can see from the code that you're using PhotoImage before creating a main window gives you an Runtime error and it is clearly said in the error that "Too early to create image" means the image cannot be create if there is no active Tk window.

The reason why some people prefer the use other module because it give you more flexibility to resize, reshape, invert and more. ( By the way it could Pillow module from PIL import Image, ImageTk How to use PIL in Tkinter ).

Now back to your code.

  1. You can randomise "O" and "X" images without even use of if-else .
  2. I created main window before creating the Image.
  3. Make sure the images you using are in the same directory.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM