os.walk() function giving stop iteration error - python

import tkinter as tk
from tkinter import *
import os
master = tk.Tk()
listbox=Listbox(master,selectmode=MULTIPLE,width=20,height=10,font=("Calibri", 12),exportselection=0)
listbox.pack(side=LEFT,fill="y")
tk.Label(master, text="Enter Folder Path ").pack(fill=tk.X,padx=120)
e1 = tk.Entry(master,width=120)
e1.pack(fill=tk.X)
path=e1.get()
folders=sorted(next(os.walk(self.path))[1],key=int)
listbox.insert(END,*self.folders)
I am trying to load listbox with the subfolder names in a directory. While running this code following error pops up:
folders=sorted(next(os.walk(self.path))[1],key=int)
StopIteration
Can someone let me know what can be done in this case? I know this issue is coming up because of os.walk function.

One reason this happens because the folder you're trying to walk through doesn't exist.
Try checking if the value in self.path does indeed ponit to a directory that is reachable.

Related

Tkinter is not showing an image, what does this error mean and how can I get the correct image to show?

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.

Assigning tkinter filedialog value to a different variable

I wish to save the filepath we get from filedialog() in a variable outside the defined function openfile().
Below is the code snippet I am using:
import tkinter as tk
from tkinter import filedialog, Button
root = tk.Tk()
def openfile():
path = filedialog.askopenfilename()
return path
Button(root, text = "click to open the stock file", command=openfile).pack(pady=20)
file_path = openfile() # this seems to be causing the issue
The problem is that the filedialog() is getting executed without even getting clicked on.
You're correct about the cause of the filedialog getting executed. Callback functions like openfile() can't return values because it's tkinter that calls them (and it ignores whatever they return). GUI programs require a different programming paradigm than you're probably used to utilized — they're event-driven. This means that they (mostly) only do things as a result of processing user input. For that reason you will need to save the result of calling the askopenfilename() function in a global variable for use later if the value isn't going to be used immediately.
tkinter provides several different kinds of variable classes — BooleanVar, DoubleVar, IntVar, and StringVar — that are good for this sort of thing. In the code below, I show how to use a StringVar to store the path.
The next step will be adding code that does something with the value getting stored in file_path. One possibility would be to add another GUI element, like a Button, that calls another function that does something with the value.
import tkinter as tk
from tkinter import filedialog, Button
root = tk.Tk()
file_path = tk.StringVar()
def openfile():
path = filedialog.askopenfilename()
file_path.set(path) # Save value returned.
Button(root, text="click to open the stock file", command=openfile).pack(pady=20)
root.mainloop()
Here’s what you can do:
def open_file():
global path
path = filedialog.askopenfilename()
And then you can access the path variable wherever you want in the program(after the function is ran, obviously.)

tkinter askdirectory syntax

I have a question about the askdirectory() in tkinter. Is it posible to use that function and also se what´s inside the folder that i want to select the directory from?
Because now when i use the function i can open the explorer and get the directory path to the folder i need but i can´t se what the folder contains (I just now that now before hand for now)... With the askdirectory function the folder says "No items match your search.". So i came up with this:
filepath_ask = filedialog.askdirectory(
initialdir=os.path.dirname(filedialog.askopenfilename(title ="Pick a folder in directory with .log files")),
title = "Press 'Select Folder'")
But it´s not that "user friendly". First it opens a window with askopenfilename so that i can see the content in the folder, then it closes when i select a file and opens a new window with askdirectory to "Select Folder" that has the content/file i chose in the window before. There must be a better way? I have been reding upp on the dokumentatin but can´t find anything that works. Help would be appreciated! Thanks
If you think that it isn't as much of a bother to have the user select a file in the askopenfilename dialog, then why not just run with that (and skip askdirectory altogether):
import tkinter as tk
from tkinter import filedialog
import pathlib
root = tk.Tk()
ask = filedialog.askopenfilename(title="Select a directory", filetypes = [("log",".log"),("All Files",".*")])
print(f"User selected Directory: {pathlib.Path(ask).resolve().parent}")
root.destroy()

When using Tkinter, error: TclError: image "pyimage8" doesn't exist

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

Simple tkinter file path reader is not working

I'm new to tkinter and I want to read in a file. This simple operation turns out to be non-trivial. Here is my code:
import tkinter as tk
from matplotlib.backends.backend_tkagg \
import FigureCanvasTkAgg ### PROBLEM 1: REMOVING THIS IMPORT CAUSES AN
### ERROR WHEN OPENING THE DIALOG
def op():
global filename
filename = tk.filedialog.askopenfilename()
root = tk.Tk()
mainframe = tk.Frame(root)
mainframe.grid(column=0, row=0)
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
tk.Button(mainframe, text="Open file", command=op).grid(column=0, row=1)
#print(filename) ### PROBLEM 2: UNCOMMENTING THIS CAUSES AN ERROR
### UNLESS I ADD <filename = ""> ABOVE THE op
### FUNCTION DEFINITION
root.mainloop()
Questions:
1) It seems very weird that importing a totally different package, matplotlib, actually has an influence over whether my program works or not. Without that import, clicking on the opening button causes an error. With it, it works fine.
Could this be a bug?
2) Why is filename not accessible outside the function body, even though I'm declaring it global? A minimal working example that has the same structure as my tkinter code is this - and this works:
def test():
global testname
testname = 23
def call_test():
test()
call_test()
print(testname)
Oddly enough, I can get my tkinter code to not produce an error, if I insert a filename = "" at the top - but I still can't actually print out the filename, it's just that the error disappears.
3) Is there any other, more elegant way to access the path of the file I'm opening without using global variables? What is the best practice?
1
I don't think it's fair to call matplotlib "...a totally different package...", let alone calling backend_tkagg that. Internally the second import also imports filedialog. That's why you don't need it. You can replace the second import simply with:
import tkinter.filedialog
2
At the time which:
print(filename)
is executed filename simply does not exist as op was never called before. Python isn't compiled, it is interpreted, it simply skips runtime error(s) until the lines that cause it are run. Try:
op()
print(filename)
to see the difference.
3
Your file path reader does work. It's just you try to print the filepath before it starts to exist, or before it has a path in it.
I think another way in the context would be:
...
def op():
global root
root.filename = tk.filedialog.askopenfilename()
print(root.filename)

Categories