i am trying to make a programme where it will print a random data from a list with a corresponding image but it is giving me an error like
> Exception in Tkinter callback Traceback (most recent call last):
> File "C:\Python39\lib\tkinter\__init__.py", line 1884, in __call__
> return self.func(*args) File "c:\Users\Fahima\Desktop\importing.py", line 24, in fun
> top.img = ImageTk.PhotoImage(Image.open(absolute_path.strip()+anime[random_choice]))
> File "C:\Python39\lib\site-packages\PIL\Image.py", line 2904, in open
> fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory:
> 'C:\\Users\\Fahima\\Desktop\\imagesnaruto.jpeg'
here is my code
import random
from tkinter import*
from PIL import Image, ImageTk
absolute_path = r'C:\Users\Fahima\Desktop\images' # your absolute path goes here(Note: Don't remove the extra space in the end)
anime = {
"1 Naruto": 'naruto.jpeg' # anime image name
}
root = Tk()
root.geometry("200x100")
def fun():
top = Toplevel(root)
top.title('Anime')
random_choice = random.choice(list(anime.keys())) #choosing random from dictionary keys
label = Label(top, text=random_choice)
label.pack()
top.img = ImageTk.PhotoImage(Image.open(absolute_path.strip()+anime[random_choice]))
image_label = Label(top, image=top.img)
image_label.pack()
can = Canvas(root, height = 100, width = 100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
b1 = Button(can,text = "Generate",command = fun,activeforeground = "black",activebackground = "yellow",pady=10)
b1.pack(side = TOP)
root.mainloop()
for the test i put only one data in the list
here is the image absolute path
You are missing a path separator between the directory and file name if you read the error message 'C:\\Users\\Fahima\\Desktop\\imagesnaruto.jpeg'
Try using
top.img = ImageTk.PhotoImage(Image.open(os.path.join(absolute_path.strip(),anime[random_choice])))
This should correctly join the path together with the correct path separator.
Related
My code currently functions as follows:
create directory --> change working directory to created directory --> option to generate .txt files into directory, viewable in a listbox --> select a .txt file from listbox and view contents in a text widget.
What I am struggling with is then finding a way to enter text and save / append to the currently open/viewed text file in the text widget.
code:
from tkinter import *
from os import mkdir, getcwd, path, listdir, chdir
def dir_gen():
curr_dir = getcwd()
print("curr dir", curr_dir)
fin_dir = path.join(curr_dir, r'note_folder')
print("fin dir", fin_dir)
if not path.exists(fin_dir):
makedirs(fin_dir)
print("directory created")
dir_gen()
flist = listdir("note_folder")
print("flist", flist)
chdir("note_folder")
def main_gui():
window = Tk()
window. geometry("400x400")
window.config(bg="#000000")
def go_home():
window.destroy()
main_gui()
print("refreshed window")
lbox = Listbox(window)
lbox.place(x=20, y=20)
listdir()
print("listdir", listdir())
for l in listdir():
lbox.insert(END, l)
add_note_entry = Entry(window)
add_note_entry.place(x=20, y=190)
add_note_entry.config(width=20)
add_line_entry = Entry(window)
add_line_entry.place(x=200, y=300)
add_line_entry.config(width=27)
def add_note():
title = add_note_entry.get()
hdl = open(title + ".txt", "w")
hdl.close(), go_home()
def open_note(event):
x = lbox.curselection()[0]
print("x", x)
file = lbox.get(x)
print("file", file)
with open(file, 'r+') as file:
file = file.read()
text_output.delete('1.0', END)
text_output.insert(END, file)
def save_note():
pass
add_note_button = Button(window, command=add_note)
add_note_button.place(x=40, y=210)
add_note_button.config(width=10, height=2, text=("ADD NOTE"))
save_note_button = Button(window, command=save_note)
save_note_button.place(x=240, y=345)
save_note_button.config(width=10, height=2, text=("SAVE NOTE"))
text_output = Text(window)
text_output.place(x=200, y=20)
text_output.config(height=15, width=20)
lbox.bind("<<ListboxSelect>>", open_note)
window.mainloop()
main_gui()
I have tried
def save_note(event):
line = add_line_entry.get()
x = lbox.curselection()[0]
file = lbox.get(x)
file = str(filename)
print("file2", file)
with open(file, 'a') as file:
file.write(line)
open_note()
and
def save_note():
x = lbox.curselection()[0]
file = lbox.get(x)
hdl = open(file, 'r+')
nt = text_output.get(1)
for l in nt:
hdl.write(l)
hdl.close()
as the main ways to get this functioning, unable to adjust either to get them running.
In the second function, tkinter does not expect the text widget get function to be indexed with an integer. Here I have recreated the second save function but edited the line nt = text_output.get(1) to nt = text_output.get('1.0', 'end'). This gets everything from the first to last character in a tkinter text widget.
def save_note():
x = lbox.curselection()[0]
file = lbox.get(x)
hdl = open(file, 'r+')
nt = text_output.get('1.0', 'end')
for l in nt:
hdl.write(l)
hdl.close()
I'm attempting to parse one or more XML files that are exported from the Bricklink website. I'm opening the file via the defusedxml ElementTree system.
Every file I attempt to open gets me OSError 22 upon the opening attempt, even with what appears to be valid filenames - I can open the files with other tools and can see the contents.
The trace is:
Traceback (most recent call last):
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:/Jason/Projects/Projects/wantedlist_modder.py", line 48, in processfiles
tree = ET.parse(filename)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\site-packages\defusedxml\common.py", line 105, in parse
return _parse(source, parser)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\xml\etree\ElementTree.py", line 1202, in parse
tree.parse(source, parser)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\xml\etree\ElementTree.py", line 584, in parse
source = open(source, "rb")
OSError: [Errno 22] Invalid argument: "'D:/Jason/Downloads/LF_LtN_2020.xml'"
The python code is as follows:
from tkinter import messagebox, filedialog
import tkinter as tk
from defusedxml.ElementTree import *
import defusedxml.ElementTree as ET
import io
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.pack(padx = 20, pady = 20)
frame = Frame(self)
frame.pack(side = TOP)
# create variable for input field
self.filename = tk.StringVar()
self.filename.set("")
# create input field
self.inputfile = tk.Entry(frame)
self.inputfile.pack(side = LEFT)
self.inputfile["textvariable"] = self.filename
# create browse button
self.browse = tk.Button(frame, text = "Browse...", command = self.openbrowse)
self.browse.pack(side = LEFT)
# create process button
self.process = tk.Button(self, text = "Process", command = self.processfiles)
self.process.pack(side = TOP, padx = 20, pady = 20)
# create quit button
self.quit = tk.Button(self, text = "QUIT", fg = "red", command = self.master.destroy)
self.quit.pack(side = BOTTOM)
def openbrowse(self):
filenames = tk.filedialog.askopenfilenames(title = 'select', filetypes = [("XML", ".xml"),])
if not filenames is None:
self.filename.set(', '.join(repr(u) for u in filenames))
def processfiles(self):
print("Roger, roger!")
filenames = tuple(self.filename.get().split(','))
showdone = 0
for filename in filenames:
try:
print(filename)
tree = ET.parse(filename)
showdone = 1
except FileNotFoundError:
tk.messagebox.showinfo("Wanted List Modder", "Please enter a valid filename")
if showdone:
tk.messagebox.showinfo("Wanted List Modder", "Done!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
I've done a lot of hunting to try to fix this but none of the fix candidates I've found on this site or elsewhere seem to change what's going on (e.g. I'm parsing from file not string). I'm not sure the contents are an issue, this seems to be something related to the filename - or the way I'm passing it to the parse function. It does print the name of the file it's processing, and I'm using the Browse button system to locate the file. I know that leads to some extra processing converting to/from tuple, but I don't think that's the culprit because the variable value passed to parse is a string.
Running Python 3.8.6 with defusedxml 0.6.0 on a Windows 7-x64 machine... and would really like assistance determining the cause of the OSError please.
Thanks in advance - and apologies if it's something simple! I haven't used Python in a while and I'm battling the adverse neurological effects of chemo...
See below - you have extra " in the file name
# your code with a bug
try:
with open('"c:/temp/a.xml"', 'rb') as f:
pass
except OSError:
print('we have a problem')
# bug was removed - it works
with open('c:/temp/a.xml', 'rb') as f:
print('it works')
def selection():
picTk = Toplevel()
picTk.title('Photos')
picTk.geometry('900x500')
image_list = os.listdir('.')
photoimage_list = []
for photo in image_list:
if photo.endswith('.gif'):
im = Image.open(photo)
pic = ImageTk.PhotoImage(file=im)
photoimage_list.append(pic)
n = 0
img_show = photoimage_list[n]
lb1 = Label(picTk,image=img_show)
lb1.image = img_show
lb1.place(x=10,y=10)
back_btn = Button(picTk,text='<<',command=lambda:back(-1),state=DISABLED)
back_btn.place(x=10,y=800)
exit_btn = Button(picTk,text='Exit',command=picTk.destroy)
exit_btn.place(x=300,y=800)
for_btn = Button(picTk,text='>>',command=lambda:forward(0))
for_btn.place(x=600,y=800)
picTk.mainloop()
tk = Tk()
tk.title('Home')
Label(tk,text='Photos of Dominic').pack(pady=10)
Button(tk,text='View Album',command=selection).pack(pady=10)
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "E:\Python2\photo album\photo_album.py", line 15, in selection
pic = ImageTk.PhotoImage(file=im)
File "C:\Python38\lib\site-packages\PIL\ImageTk.py", line 89, in __init__
image = _get_image_from_kw(kw)
File "C:\Python38\lib\site-packages\PIL\ImageTk.py", line 58, in _get_image_from_kw
return Image.open(source)
File "C:\Python38\lib\site-packages\PIL\Image.py", line 2852, in open
prefix = fp.read(16)
AttributeError: 'GifImageFile' object has no attribute 'read'
When I clicked the button View Album then the above error message appeared. I tried a lot of times within a day and a blank window appears with no image. I keep changing and use different methods but there is still error. I also searched with different books and use the correct format already but error appears all the time. My aim is to show the picture on the second window within clicking the button View Album. If possible can anyone teach me how to solve this problem? I really need help to solve the above problem.
If my understanding is correct you are opening the image with Image.open() then you are passing it as a file to ImageTk.PhotoImage(). To resolve this you could use ImageTk.PhotoImage(image=im) or simply delete Image.open(photo) and use ImageTk.PhotoImage(file=photo) I hope this helps.
def selection():
picTk = Toplevel()
picTk.title('Photos')
picTk.geometry('900x500')
image_list = os.listdir('.')
photoimage_list = []
for photo in image_list:
if photo.endswith('.gif'):
pic = ImageTk.PhotoImage(file=photo) # file is photo not im
photoimage_list.append(pic)
So I am trying to write some code that needs to search through a .txt file and return the results to a basic GUI I have created. Here is my code so far. When I click the "search" button in the GUI, nothing happens.
My code so far:
import re
from tkinter import *
def query():
search = lookfor.get()
datafile = open("data.txt", "r")
for line in datafile.readlines():
if re.query(search, line, re.I):
findings.insert(INSERT)
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings.pack()
root.mainloop()
I've also tried a different way of searching the txt file:
import re
from tkinter import *
def query():
datafile = open("data.txt", "r")
for line in datafile:
line = line.strip()
elements = line.split("\t")
if str(lookfor.get()) in elements[0]:
findings.insert(INSERT, elements[1])
elif str(lookfor.get()) in elements[1]:
findings.insert(INSERT, elements[0])
findings.insert(END, '\n')
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings .pack()
root.mainloop()
Upon running your program, (after fixing the query() issue), it produces an AttributeError:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/usr/Documents/main.py", line 9, in query
if re.query(search, line, re.I):
AttributeError: module 're' has no attribute 'query'
Instead of using re.query() (which doesn't exist), use re.search() (which takes the exact same parameters).
Also, there is a TypeError on line 10:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/usr/Documents/main.py", line 10, in query
findings.insert(INSERT)
TypeError: insert() missing 1 required positional argument: 'chars'
This is fixed by changing the line from:
findings.insert(INSERT)
To:
findings.insert(INSERT, line)
Putting this all together gives the following program:
import re
from tkinter import *
def query():
search = lookfor.get()
datafile = open("data.txt", "r")
for line in datafile.readlines():
if re.search(search, line, re.I):
findings.insert(INSERT, line)
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings.pack()
root.mainloop()
Hope that helps!
I'm trying to create a program with Tkinter and tkFileDialog that opens a file for reading and then packs it into a text widget but, whenever I run this:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(str(file), "r+")
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
I get this:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:\Users\super\PycharmProjects\untitled1\File Picker.py", line in filefind
f = open(str(file), "r+")
IOError: [Errno 22] invalid mode ('r+') or filename: "<open file u'C:/Users/super/PycharmProjects/untitled1/util.h', mode 'r' at 0x00000000026E0390>"
Here is the issue; askopenfile() is returning an object, not just the name. If you print file, you will get <_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>. You want the name= from the object. To get that, all you need to do is replace f = open(str(file), "r+") with f = open(file.name, "r+").
Here is how it will look in your code:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(file.name, "r+") # This will fix the issue.
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
Edit
A cleaner way of doing this is by letting askopenfile() do the work of opening a file instead of 're-opening' it again with open(). Here is the cleaner version:
file = askopenfile()
x = file.read()