I'm making a web scraping on a website for a private game server using Python. In a part of this website prints the result of the last nation war winner and show 2 messages: "Capella Ganhou!!" and "Procyon Ganhou!!" using the BeautfulSoup library. I made a condition for each event for show the winner nation image into the Label by an url. But for some reason it shows always the last image url and I don't know what is happening. Here is the code below:
from tkinter import *
import urllib.request
from bs4 import BeautifulSoup
from IPython.display import Image, display
from PIL import Image, ImageTk
from io import BytesIO
def capella_tg():
resultado_tg = StringVar()
try:
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg, font=("Consolas", 25)).pack()
except:
return False
def procyon_tg():
resultado_tg = StringVar()
try:
resultado_tg.set(soup.find_all("font")[4].string[3:])
label_resultado_tg = Label(root, textvariable=resultado_tg, font=("Consolas", 25)).pack()
except:
return False
root = Tk()
root.title("Resultado TG Cabal Ghost")
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
if capella_tg():
url = "https://i.imgur.com/AHLqtt0.jpg"
with urllib.request.urlopen(url) as u: raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = Label(image=image).pack()
else:
procyon_tg()
url = "https://i.imgur.com/TQyCnfD.jpg"
with urllib.request.urlopen(url) as u: raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = Label(image=image).pack()
root.mainloop()
Related
I need some help! This is my code. When i press run it isn't do anything.
I've tried to install again all the modules, but no luck.
from tkinter import *
from tkinter import filedialog
import pyttsx3
from PyPDF2 import PdfFileReader
#Intializing Window
window = Tk('500x350')
window.geometry()
window.config(bg='#6C969D')
window.title("Pdf to Audio Speecch |Nick S")
#Labels
startingpagenumber = Entry(window)
startingpagenumber.place(relx=0.6,rely=0.1)
page1 = Label(window,text="Enter starting page number")
page1.place(relx=0.2,rely=0.1)
label = Label(window, text="Select a book.")
label.place(relx=0.3, rely=0.2)
def file():
path = filedialog.askopenfilename()
book = open(path, 'rb')
pdfreader = PdfFileReader(book)
pages = pdfreader.numPages
speaker = pyttsx3.init()
for i in range(int(startingpagenumber.get()), pages):
page = pdfreader.getPage(i)
txt = page.extractText()
speaker.say(txt)
speaker.runAndWait()
B = Button(window, text="Choose the Book", command=file)
B.place(relx=0.4,rely=0.3)
This is what I get in console
C:\Users\nicks\Desktop\Coding Projects\Python\Pdf to Audio>C:/Users/nicks/AppData/Local/Microsoft/WindowsApps/python3.9.exe "c:/Users/nicks/Desktop/Coding Projects/Python/Pdf to Audio/main.py"
Thanks everyone!
The problem was that I didn't include mainloop() in the end!
import io
import base64
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except ImportError:
# Python3
import tkinter as tk
from urllib.request import urlopen
def display_poster(image_url, x, y):
# image_url = "http://i46.tinypic.com/r9oh0j.gif"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodebytes(image_byt)
photo = tk.PhotoImage(data=image_b64)
# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')
# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(x, y, image=photo, anchor='nw')
def btn_clicked():
display_poster("http://i46.tinypic.com/r9oh0j.gif", 630, 350)
I have tried the base64 package solution but its not working.
It would be nice if someone could help me out with the pakages i need to import and the function to display the image using Canvas.
use this snippets, its work fine :
import tkinter as tk
import urllib.request
#import base64
import io
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Weather")
link = "http://i46.tinypic.com/r9oh0j.gif"
class WebImage:
def __init__(self, url):
with urllib.request.urlopen(url) as u:
raw_data = u.read()
#self.image = tk.PhotoImage(data=base64.encodebytes(raw_data))
image = Image.open(io.BytesIO(raw_data))
self.image = ImageTk.PhotoImage(image)
def get(self):
return self.image
img = WebImage(link).get()
imagelab = tk.Label(root, image=img)
imagelab.grid(row=0, column=0)
root.mainloop()
Output:
I have an animated .webp file which is hosted online and I tried to display it using Tkinter.Here is my code.
import urllib.request
from PIL import Image, ImageTk
root=tkinter.Tk()
u = urllib.request.urlopen("https://..../.....webp")
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im.resize((470,210)))
Label(root,image=image).pack()
root.mainloop()
This works without raising any errors but only displays one frame.Why is that so?
Is there any way how I can solve this issue
Based on #Atlas435's comment I have made a code which can display webp files in tkinter without downloading them.This is the code:
from io import BytesIO
from tkinter import *
import tkinter
import urllib.request
from PIL import Image, ImageTk
root=tkinter.Tk()
ar=0
import tkinter as tk
from PIL import Image, ImageTk
u = urllib.request.urlopen(url)
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
from itertools import count
class ImageLabel(tk.Label):
"""a label that displays images, and plays them if they are gifs"""
def load(self, im):
if isinstance(im, str):
im = im
self.loc = 0
self.frames = []
try:
for i in count(1):
self.frames.append(ImageTk.PhotoImage(im.copy().resize((470,210))))
im.seek(i)
except EOFError:
pass
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(self.frames) == 1:
self.config(image=self.frames[0])
else:
self.next_frame()
def unload(self):
self.config(image="")
self.frames = None
def next_frame(self):
if self.frames:
self.loc += 1
self.loc %= len(self.frames)
self.config(image=self.frames[self.loc])
self.after(self.delay, self.next_frame)
lbl = ImageLabel(root)
lbl.pack()
lbl.load(im)
root.mainloop()
I'm able to display an image if I grab it from one location, but I need the image to update along with the related article from a website. So if you open my application tomorrow, a different image will appear. So needless to say, I'm using regular expressions but the image just won't show on the label. Here's my code so far:
from Tkinter import *
import Tkinter as tk
import re
from re import findall
from urllib import urlopen
import datetime
from PIL import Image
from PIL import Image, ImageTk
from cStringIO import StringIO
root = Tk()
root.title("Science and Technology")
root.geometry("600x600")
main_label = Label(root, text = "Science and Technology")
main_label.pack()
all_image_height = 400
all_image_width = 400
dash = "-"
now = datetime.datetime.now()
text_area = LabelFrame(root, borderwidth = 2)
text_area.pack(padx = 10, pady = 10, expand = 1, fill= BOTH)
date = Label(text_area)
date.pack()
content_t = Label(text_area)
content_t.pack()
imag = Label(text_area)
imag.pack()
def science_all():
sw_img = 300
sh_img = 300
webScience = urlopen(urlScience)
html_code = webScience.read()
webScience.close()
titl = findall("'name'>(.+[a-zA-Z])</title>", html_code)[0]
date1 = str(now.day),(dash),(now.month),(dash),(now.year)
content_title = findall('itemprop="name">(.+[a-zA-Z])</h5>',html_code)[0]
text_area.config(text = titl)
date.config(text = date1)
content_t.config(text = content_title)
url2 = "http://www.wired.com/"
im = urlopen(url2)
html_code2 = im.read()
im.close()
global image_file
global photo_image
global imag
imag2 = findall('<img src="(.*)">', html_code2)
image_file = Image.open(StringIO(html_code2))
photo_image = ImageTk.PhotoImage(image_file)
imag.config(image=imag2)
Science = Button(root, text="Science",
command = science_all)
Science.pack(side=LEFT)
urlScience = 'http://www.wired.com/'
root.mainloop()
It works fine when using a link for one specific image from a website but when regular expressions come into it, that's where it all gets difficult for me. Any suggestions would be very helpful. Thanks.
I am making a app with python and Tkinter. Say I added two buttons one for MAIN and one for NEWS when I press MAIN make the function mainthumsfun run and set the variables and after that run gui function with the new variables. How would I make that work?
import StringIO
import Scraper
import Tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
root.title('RazeTheWorld')
maintumbs = Scraper.maintumbs()
newstumbs = Scraper.newstumbs()
def mainthumsfun():
url0 = mainthumbs[0]
url1 = mainthumbs[1]
url2 = mainthumbs[2]
url3 = mainthumbs[3]
def newsthumbsfun():
url0 = newsthumbs[0]
url1 = newsthumbs[1]
url2 = newsthumbs[2]
url3 = newsthumbs[3]
def gui():
imgf1 = urllib.urlopen(url0)
imgwr1 = StringIO.StringIO(imgf1.read())
image1 = ImageTk.PhotoImage(Image.open(imgwr1))
panel1 = tk.Label(root, image=image1)
panel1.grid(row=0,column=0)
imgf2 = urllib.urlopen(url1)
imgwr2 = StringIO.StringIO(imgf2.read())
image2 = ImageTk.PhotoImage(Image.open(imgwr2))
panel2 = tk.Label(root, image=image2)
panel2.grid(row=1,column=0)
imgf3 = urllib.urlopen(url2)
imgwr3 = StringIO.StringIO(imgf3.read())
image3 = ImageTk.PhotoImage(Image.open(imgwr3))
panel3 = tk.Label(root, image=image3)
panel3.grid(row=2,column=0)
imgf4 = urllib.urlopen(url4)
imgwr4 = StringIO.StringIO(imgf4.read())
image4 = ImageTk.PhotoImage(Image.open(imgwr4))
panel4 = tk.Label(root, image=image4)
panel4.grid(row=3,column=0)
root.mainloop()
You just want buttons that run code when clicked?
What you do is draw a widget within your root Frame, such as a button or a menu field.
Check out this example text editor
It's a text editor with a menu and a couple of buttons calling a method when you click 'it. No more. Easy to grok :)