Python Tkinter Error (Weather API) - python

I have this program which uses a Weather API and gets the weather of a city.
The city is read from a text file.
Here's the Python File:
import urllib2
import json
from string import capitalize
import Tkinter as tk
city = ''
data = open('data.txt', 'r+')
for i in data:
if 'current_city' in i:
index = len(i)
city = i[13:index]
print city
def kelvinToCelsius(kelvin_temp):
return str(int(kelvin_temp)-273) + ' Degree Celsius'
def setText(string, string_var):
string_var.set(string)
def getCurrentTemperature(city):
city = city.replace(' ', '%20')
url_to_call = 'http://api.openweathermap.org/data/2.5/weather?q=' + city
response = urllib2.urlopen(url_to_call)
json_obj = json.load(response)
print url_to_call
current_desc = capitalize(json_obj['weather'][0]['description'])
current_temp = kelvinToCelsius(json_obj['main']['temp'])
setText(city, city_name_label_text_var)
return current_desc + ': ' + current_temp
maingui = tk.Tk()
city_temp_and_desc_label_text_var = tk.StringVar()
city_name_label_text_var = tk.StringVar()
main_frame = tk.Frame(maingui, width=500, height=200, borderwidth=2)
main_frame.pack()
city_name_label = tk.Label(main_frame, textvariable=city_name_label_text_var, font=12).place(x=226, y=0)
city_temp_and_desc_label = tk.Label(main_frame, textvariable=city_temp_and_desc_label_text_var, font=30).place(x=140, y=99)
setText(getCurrentTemperature(city), city_temp_and_desc_label_text_var)
tk.mainloop()
Please help! I learned from the error that the problem is that the city name is not read from the text file properly and is equal to '' when it is passed to the url.
I tried many different ways to avoid this error but none of them worked.
EDIT: I forgot to mention but an initial program writes the text to the text file and then runs the above python script. I also forgot to mention this but when the above file is run directly, it works. But when I checked the rerouting python script writes properly to the text file.
Here's the error:
Traceback (most recent call last):
File "D:\Anand\Coding\Eclipse IDE\eclipse\WorkBench\The Weather\src\__main__.py", line 54, in <module>
setText(getCurrentTemperature(city), city_temp_and_desc_label_text_var)
File "D:\Anand\Coding\Eclipse IDE\eclipse\WorkBench\The Weather\src\__main__.py", line 35, in getCurrentTemperature
current_desc = capitalize(json_obj['weather'][0]['description'])
KeyError: 'weather'

Related

Making a list with corresponding image

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.

Python OSError 22 in parsing XML file that exists and has valid filename

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

Using .split with tkinter

Quite a beginner here. I have a command line script that works fine for what I do and I'm looking to move it into a GUI.
os.chdir(ImageDirST)
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
print(f, "-->", n_name)
I would like this to display in the same fashion within a message window in tkinter.
With some help from here, I managed to print the filenames in the directory when a button is pushed with:
filenames = sorted(os.listdir(ImageDirBT))
text = "\n".join(filenames)
print_filename_test.set(text)
I have tried to use my split code to setup a list of what the new filenames would look like, prior to setting the variable, with the following, where print_filenames() is the function triggered by the press of a button.
def print_filenames():
filenames = sorted(os.listdir(ImageDirBT))
for filenames in sorted(os.listdir(ImageDirBT)):
f_name,f_ext = (os.path.splitext(filenames))
f_sku = (f_name.split('_')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
newlist = "\n".join(n_name)
print_filename_test.set(newlist)
I don't get any errors with this code for print_filenames(), however what is displayed in the message panel is the last filename in the list, vertically, one character wide:
eg:
F
I
L
E
_
1
1
.
e
x
t
I would like to display the output as:
oldfilename_01.ext --> newfilename_csvdata_01.ext
oldfilename_02.ext --> newfilename_csvdata_02.ext
oldfilename_03.ext --> newfilename_csvdata_03.ext
oldfilename_04.ext --> newfilename_csvdata_04.ext
The command line program I have written uses numbers to chose menu options for what needs to be done, confirming before any renaming is done, hence printing the file name comparisons. My struggle is manipulating the strings in the list to be able to do the same thing.
Using messagebox:
import os
import tkinter as tk
from tkinter import messagebox
ImageDirST = r"your_path"
os.chdir(ImageDirST)
root = tk.Tk()
names = []
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
names.append(f"{f} --> {n_name}\n")
messagebox.showinfo(title="Something", message="".join(names))
root.mainloop()
Or using Text widget with scrollbar:
import os
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
ImageDirST = r"your_path"
os.chdir(ImageDirST)
root = tk.Tk()
txt = ScrolledText(root, font="Arial 8")
txt.pack()
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
txt.insert("end",f"{f} --> {n_name}\n")
root.mainloop()

Trying to return search results from a txt file to GUI

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!

AttributeError: 'module' object has no attribute 'urlopen' (Python 2.7)

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

Categories