I am trying to learn how to add images to tkinter (using a lot of youtube codemy videos). I have a kingdom management game I have been writing where I have been able to successfully add images as labels and as buttons and have them update as you progress through seasons of time in game.
However, when I started a new py file to work on a separate part of the code, suddenly Pycharm could not find any of the images and I got a:
"tkinter.TclError: couldn't open "summer.png": no such file or directory".
So, I copied my code that worked in the main instance in a separate py file and it still does not work and I get the same error. So, for whatever reason, in one file the same code is able to be used and it finds the png but in a second instance (with the "same" code) it cannot. Also, hovering over the image path allows me to see the image in Pycharm so I know it is still there (the images are in the same folder as my python project). I am wondering if there is something simple I am not seeing. All the below image paths work in my main program but it fails when I attempt to replicate it.
from tkinter import *
import pickle
import random
from pathlib import Path
root = Tk()
root.title("The Crumbling Kingdom")
root.geometry("1300x800")
bgsummer = PhotoImage(file="summer.png")
worldmap = PhotoImage(file="map1.png")
bgspring = PhotoImage(file="spring.png")
bgwinter = PhotoImage(file="winter.png")
bgfall = PhotoImage(file="fall.png")
worldmap = PhotoImage(file="map1.png")
table = PhotoImage(file="table.png")
side = PhotoImage(file="side.png")
backgroundimage = bgspring
my_background=Label(root, image= backgroundimage)
my_background.place(x=0,y=0, relwidth = 1, relheight =1)
Related
My project has multiple tkinter functions that create windows and different buttons have different buttons that connect to the main program. One issue I have is that when I call a tkinter gui function the images are not displayed.
def get_userInfo(user,pass):
login_state = db.login_verification(user,pass) # Returns either True / False
if login_state == True:
full_name = db.retrive(user,pass,id) # Get's Full name from database.
gui.user_page(first_name) # This only displays the window with no images / text.
gui.user_page("john") # This works perfectly tho
When I call a function within a function the images from the assets path do not load.
Whereas if I just do gui.user_page from outside the function it works without any issues.
I think if I were to use more classes in my gui.py file it should probably fix the issue.
I am creating a dice roller in VSCode with Python for a class and we are to use Tkinter to create our widget to achieve this. I followed a tutorial to a T and yet I am still receiving errors saying the images do not exist. I have tried making my images .gif and .png and neither works.
Here is the code:
import tkinter as tk
from PIL import Image, ImageTk
import random
root = tk.Tk ()
root.title("Cassie's Dice Roller")
root.geometry("500x500")
six_dice= ["one.png" , "two.png" , "three.png" , "four.png" , "five.png" , "six.png"]
roll_one = ImageTk.PhotoImage(Image.open(random.choice(six_dice)))
label = tk.Label(root, image=roll_one)
label.pack(side=tk.CENTER)
def six_roll():
roll_one = ImageTk.PhotoImage(Image.open(random.choice(six_dice)))
label.configure(image=roll_one)
label.image=roll_one
Button = tk.Button(root, text='Roll', foreground='blue', command='six_roll')
Button.pack()
root.mainloop()
Here is the error I'm receiving:
File "C:\Users\brind\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\Image.py", line 2953, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '4.gif'
When I ran this code I got no similar error. The only problem was with the image.CENTER statement within the pack. But remove that and the code ran fine. I would try out an absolute path to the images as they don't seem to be appearing in your run level directory.
Where have you stored the pictures? You can get the location which the python interpreter searches files through
os.getcwd()(link):
Return a string representing the current working directory.
In default, it's the path of the workspace folder, because it's the default value in the terminal.
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.
You can randomise "O" and "X" images without even use of if-else.
I created main window before creating the Image.
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()
I keep getting the error, TclError: image "pyimage8" doesn't exist.
It is strange, as the number increases every time I run it?
I'm running python using spyder, dunno whether this affects anything.
Here is my code:
#import tkinter
import Tkinter as tk
homescreenImage = PhotoImage(file="Homescreen.gif")
#create a GUI window.
root = Tk()
#set the title.
root.title("Welcome to the Pit!")
#set the size.
root.geometry("1100x700")
homescreenFrame = tk.Frame(root, width=1100, height = 700)
homescreenFrame.pack()
homescreenLabel = tk.Label(homescreenFrame, image=homescreenImage)
homescreenLabel.pack()
#start the GUI
root.mainloop()
I found that my script would run once and then give me an error on subsequent runs. If I restarted the console, it would run again. I solved the problem by using the following code in the beginning of my script:
import sys
if "Tkinter" not in sys.modules:
from Tkinter import *
It works every time now.
If you import Tkinter as tk you should use the alias tk when calling tk, eg. root = tk.Tk(). Otherwise Python will not find Tk.
You don't need to import PIL for this.
You can not create a Photoimage before you create Tk.
Try this:
import Tkinter as tk
root = tk.Tk()
root.title("Welcome to the Pit!")
root.geometry("1100x700")
homescreenImage = tk.PhotoImage(file="Homescreen.gif")
homescreenFrame = tk.Frame(root, width=1100, height = 700,)
homescreenFrame.pack()
homescreenLabel = tk.Label(homescreenFrame, image=homescreenImage)
homescreenLabel.pack()
root.mainloop()
Be kind and paste the whole error message in your question also.
Following could be the errors:
1) Give the whole path to the file name
eg: "/home/user/Homescreen.gif"
2) If you are using windows and the above doesn't work:
use "\\C:\\home\\Homescreen.gif" (this is because, windows gets confused)
3) If that also, doesn't work, ensure that the directory of your python
program is the same as that of the image.
4) Also, create the photoimage only after you have created the root
window.
5) For some reason, while running in the debugger, if any previous
executions had thrown errors I get the "pyimage doesn't exist" error.
However, if I restart the debugger (or no previously executed scripts
have thrown errors), then the program runs fine.
6) Also, don't import PIL, it's not required.
Try all the above, if it doesn't work let me know.
Hope this helps.
i think this could be due to :
tkinter only supports .png format for images
Yet, there are other ways to add .gif`` instead of PhotoImage```
In my case, it was because I forgot to keep a reference to the image. Try adding this line after creating the label:
homescreenLabel.image=homescreenImage.
You should use Toplevel window that is directly managed by the window manager.
Just change :
root = Tk() to root = Toplevel()
I wrote a little application, that saves small videos it generates. The code pasted should do the following:
show dialog to the user to choose a directory
if directory is not empty show widget that has a circle running around so there's a feedback that something is going on
then generate the movies (which takes some time and most if it has handled with multiprocessing pool)
(not included in snippet, but the code would go on to do more background stuff, so the loading widget would stay on for a while
Code:
def saveMovie(self):
self.pause()
if not os.path.exists("outputs"):
os.makedirs("outputs")
dir = QtGui.QFileDialog.getExistingDirectory(self,dir="outputs",options=QtGui.QFileDialog.ShowDirsOnly)
if not dir == '':
self.loading = True
self.loadingWidget.show()
name = os.path.basename(dir) + "_"
settings = sm.fetch_settings()
swarms,l,l1,l2 = self.generate_movies()
Now instead of this, what happens is that the dialog disappears and the loading widget is shown only after the program has existed from self.generate_movies(). What am I missing?