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()
Related
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.
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 am trying to write to a file that I just created using the filedialog.asksaveasfile. I set the mode to 'w'. Do I have to open the file again or something?
f = filedialog.asksaveasfile(mode='w', defaultextension=".csv")
keyList = []
for n in aDict.keys():
keyList.append(n)
keyList = sorted(keyList, key=operator.itemgetter(0,1))
csvWriter = csv.writer(f)
for key in keyList:
sal1 = aDict[(key[0],key[1])][0]
sal2 = aDict[(key[0],key[1])][1]
csvWriter.writerow(key[0], key[1], sal1, sal2)
f.close()
You can simply use the write function of the reference (of type _io.TextIOWrapper) returned by the asksaveasfile function.
For example
from tkinter import filedialog, Tk
root = Tk().withdraw()
file = filedialog.asksaveasfile(mode='w', defaultextension=".csv")
if file:
file.write("Hello World")
file.close()
Note that the object returned by the asksaveasfile function is of the same type or class of the object returned by the built-in open function. Note also that the same function returns None, if Cancel is pressed when the dialog pops up.
I am writing a program for my school, and I'm hosting the daily SBWATs (Students Will Be Able To) for each teacher in text files. Here is my code, SchoolNet.py
import Tkinter
import urllib
print urllib.__file__
def showsbwat(teacher):
sbwat = urllib.openurl("192.168.1.203/" + teacher + ".txt")
print sbwat
def showshecdule():
mainwindow.withdraw()
schedulewindow.deiconify()
firstperiodbutton = Tkinter.Button(schedulewindow, text = periodlist[0], command = lambda: showsbwat(periodlist[0]))
firstperiodbutton.pack()
global sbwatlabel
sbwatlabel = Tkinter.Label(schedulewindow, text = "")
sbwatlabel.pack()
def login():
try:
schedulefile = open(usernamevar.get() + ".txt", "r")
global periodlist
periodlist = schedulefile.readlines()
print periodlist
mainwindow.deiconify()
loginwindow.withdraw()
except:
usernamevar.set("Invalid ID")
loginwindow = Tkinter.Tk()
loginwindow.wm_title('Login to SchoolNet')
mainwindow = Tkinter.Tk()
mainwindow.wm_title('SchoolNet')
schedulewindow = Tkinter.Tk()
schedulewindow.wm_title('SchoolNet Schedule')
mainwindow.withdraw()
schedulewindow.withdraw()
loginwindow.deiconify()
schedulebut = Tkinter.Button(mainwindow, text = 'Schedule', command=showshecdule)
schedulebut.pack()
usernamevar = Tkinter.StringVar()
usernameentry = Tkinter.Entry(loginwindow, textvariable=usernamevar)
usernameentry.pack()
loginbut = Tkinter.Button(loginwindow, text="Login", command=login)
loginbut.pack()
Tkinter.mainloop()
But, when I run it, I keep getting this error:
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "SchoolNet.py", line 12, in <lambda>
firstperiodbutton = Tkinter.Button(schedulewindow, text = periodlist[0], com
mand = lambda: showsbwat(periodlist[0]))
File "SchoolNet.py", line 6, in showsbwat
sbwat = urllib.openurl("192.168.1.203/" + teacher + ".txt")
AttributeError: 'module' object has no attribute 'openurl'
I have tried this with urllib and urllib2, but I get the same error. None of the other files in the directory are named the same of any python modules. What am I doing wrong?
I'm using Python 2.7
It is urlopen not openurl:
urllib.urlopen()
from urllib.request import urlopen
URL = "www.webpage-address"
page= urlopen(URL)
text = page.read()
When i run this code i get an error saying the file does not exist, i have created the file and linked back to them by copying the directory from the save part. I can also see the file and have triple checked the name etc but it still won't work can someone help.
from tkinter import *
import os.path
master= Tk()
master.geometry('500x500+0+0')
def print_value(val):
print ("c1="+str (c1v.get()))
print ("c2="+str(c2v.get()))
c1v=DoubleVar()
c2v=DoubleVar()
c1 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c1v)
c1.grid(row=1,column=1)
c2 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c2v)
c2.grid(row=1,column=2)
def func():
pass
file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt")
val1, val2 = (x.split("=")[1] for x in file1)
c1.set(val1)
c2.set(val2)
file1.close()
def record():
save_path = 'C:/Users/Josh Bailey/Desktop/pi_dmx'
name_of_file = ("preset_test ")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName , "w")
toFile = ("c1="+str (c1.get())+ "\n""c2="+str(c2.get()))
file1.write(toFile)
file1.close()
master.mainloop()
rec=Button(master, text="Record",width=20, height=10, bg='Red', command=record)
rec.grid(row=2, column=1)
load=Button(master, text="Load",width=20, height=10, bg='gold',command=func)
load.grid(row=2, column=2)
the error is-
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python33\lib\idlelib\run.py", line 121, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "C:\Python33\lib\queue.py", line 175, in get
raise Empty queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args) File "C:\Users\Josh Bailey\Desktop\save test.py", line 24, in func
file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt") FileNotFoundError: [Errno 2]
No such file or directory: 'C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt'
Inside func, you specify the filepath as being:
C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt
However, your record function makes it to be:
C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test .txt
# Note the extra space here--^
Because of this, Python will not be able to find the file.
To fix the problem, remove the space on this line in record:
name_of_file = ("preset_test ")
# here--^
Now record will create the filepath to be what it should.
Also, that pass inside of func should not be there. It does nothing.
You're on Windows right? Replace the slashes with backslashes, \, and add a "r" infront of the string, like this:
file1 = open(r"C:\Users\Josh Bailey\Desktop\pi_dmx\preset_test.txt")
Hope this works