'Variable not being assigned and called correctly
I am trying to get a picture from my files to print after the user input a number for PokeID in the interactive manual. But when the number is entered it does not run into file_type. I do not know if I am calling it correctly. StackOverflow is telling me to add more details but I do not know what else to say. Why is the user input not running into the file?
from IPython.display import display, HTML, Image, clear_output
from IPython.display import Image, Audio
from ipywidgets import interact_manual
import glob
import requests
import lxml.html as lh
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
display(HTML("<h1> Ud's <font color= 'red'>PokeDex</font> </h1>"))
pokedexpic = "https://img.icons8.com/color/480/pokedex.png"
display(Image(url=pokedexpic, width=200))
display(Audio(filename="pokesong.mp3"))
url='http://pokemondb.net/pokedex/all'
website = requests.get(url)
doc = lh.fromstring(website.content)
tr_elements = doc.xpath('//tr')
col=[]
i=0
for t in tr_elements[0]:
i+=1
name=t.text_content()
col.append((name,[]))
for j in range(1,len(tr_elements)):
T=tr_elements[j]
if len(T)!=10:
break
i=0
for t in T.iterchildren():
data=t.text_content()
if i>0:
try:
data=int(data)
except:
pass
col[i][1].append(data)
i+=1
Dict={title:column for (title,column) in col}
df=pd.DataFrame(Dict)
src_path = "/home/jovyan/library/ist256/spring2022/lessons/Project/PokeImages/"
no_of_image_to_show = 1
@interact_manual(Pokemon = df['Name'])
def main(Pokemon):
print(df[ df['Name'] == Pokemon ])
@interact_manual(PokeID = "") #PokeID wont run into file_type to print png
def main(PokeID):
file_type = f"{PokeID}.png"
def display_n_images(src_path, file_type, no_of_image_to_show):
image_folder = glob.glob(src_path + file_type)
image_folder = image_folder[0:no_of_image_to_show]
for a_image in image_folder:
display(Image(filename=a_image))
print(a_image)
display_n_images(src_path, file_type, no_of_image_to_show)
Solution 1:[1]
That's right, you are interacting with file_type
incorrectly. You refer to it outside of the inner function main
, where this variable is defined as local. The minimum change required for your code to work is to declare file_type
as a global variable.
...
@interact_manual(Pokemon = df['Name'])
def main(Pokemon):
display(df[ df['Name'] == Pokemon ])
@interact_manual(PokeID = "")
def main(PokeID):
global file_type # make file_type available globally
file_type = f"{PokeID}.png"
print(file_type)
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |