Issue with showing and updating image in Tkinter - python

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.

Related

Python script using Tkinter for displaying sensor readings over background image displaying correctly

So I'm making a script for a raspberry pi 3-b. The idea is to take sensor readings from 4 sensors, and display each reading, updating over time, in each corner overtop of a background image. I am mostly unfamiliar with python, and new to tkinter.
The following is my current code.
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
window = Tk()
def main():
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
text1 = tk.StringVar()
text2 = tk.StringVar()
text3 = tk.StringVar()
text4 = tk.StringVar()
myFont = tkfont.Font(family="Titillium Web", size=32)
c.create_text(10,10,text=text1,fill="yellow",font=myFont)
c.create_text(10,450,text=text2,fill="yellow",font=myFont)
c.create_text(750,10,text=text3,fill="yellow",font=myFont)
c.create_text(750,450,text=text4,fill="yellow",font=myFont)
c.pack()
def update():
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
text="Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1)
text="Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2)
text="Temperature3={0:0.1f}*C Humidity3={1:0.1f}%".format(temperature3, humidity3)
text="Temperature4={0:0.1f}*C Humidity4={1:0.1f}%".format(temperature4, humidity4)
window.after(100, update)
main()
update()
window.mainloop()
For some reason, my image is displaying as a blank gray background and my text is not displaying the readings or updating. instead I get this
What am I doing wrong, can anyone please explain what is going wrong here and how I might fix it?
With advice from some of the comments, I produced this, It works well. Thanks guys
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
window = Tk()
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
myFont = tkfont.Font(family="Titillium Web", size=32)
textVar1 = tk.StringVar()
textVar2 = tk.StringVar()
textVar3 = tk.StringVar()
textVar4 = tk.StringVar()
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
text1 = c.create_text(10,10,text=textVar1.get(),fill="yellow",font=myFont)
text2 = c.create_text(10,450,text=textVar2.get(),fill="yellow",font=myFont)
text3 = c.create_text(750,10,text=textVar3.get(),fill="yellow",font=myFont)
text4 = c.create_text(750,450,text=textVar4.get(),fill="yellow",font=myFont)
c.pack()
def update():
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
c.itemconfigure(text1, text=textVar1.get())
c.itemconfigure(text2, text=textVar2.get())
c.itemconfigure(text3, text=textVar3.get())
c.itemconfigure(text4, text=textVar4.get())
window.after(100, update)
update()
window.mainloop()

Returning always the last image into Label

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

how Write a text on png image Using python PIL

I am trying to code for make a registration System and Identity Card printer first form done with making data import to database using sqlite3 database and tkinter GUI.this form for get data from database and write that data text on png image.that png image after written data it is the identity card.
**so this is the problem..code run without any errors.but image not written data.for try this code firstly i didn't use database data.i used data from string variable **
import sqlite3
from tkinter import Tk, Button, Canvas
from PIL import Image, ImageFont, ImageDraw
connection = sqlite3.connect("school.db")
tao = Tk()
tao.title("Mayurapada Central Collage")
tao.configure(bg = '#6699ff')
canvas = Canvas(tao,width = 600,height = 400,bg = '#6699ff')
def imgs():
img = Image.open("C:\\Users\\TAO\\Desktop\\New\\02.png")
#img.show()
str01 = "Hello World"
font = ImageFont.truetype("arial.ttf",200)
w,h = font.getsize(str01)
print(str01)
draw = ImageDraw.Draw(img)
draw.text(((900-w)/2,(900-h)/2),str01,font = font,fill = "black")
img.show()
button01 = Button(tao,text = "Preview",bd = 7,padx = 5,pady = 5,command =
imgs).place(x = 50,y = 300)
canvas.pack()
tao.mainloop()

Image viewer/ images for buttons

I'm trying to implement simple image viewer, where you can choose from 2 pictures. I have one menubutton which offers these pictures. After choosing one of the images, the program creates 3 or 5 buttons. I would like to append to each of these buttons different images, so the first button would have one image and the second button would have another image and so on. I've created a function with for loop to create these buttons, but can't move on from that point. I can append one image to all of them, but can't do that one by one with different images.
Thanks for help
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
from functools import partial
from PIL import Image, ImageTk
class Halabala():
def __init__(self):
self.master = tk.Tk()
self.master.geometry("1100x700")
self.lists_labels = []
self.rbutton = tk.Menubutton(self.master, text = "Choose picture")
self.picks2 = tk.Menu(self.rbutton)
self.rbutton.config(menu=self.picks2)
self.picks2.add_command(label = "Spider", command = partial(self.create_labels,3))
self.picks2.add_command(label = "Sugar", command = partial(self.create_labels,5))
self.rbutton.config(width = 30, bg = "white", bd = 5, relief = tk.RAISED)
self.rbutton.place(x = 900, y = 30)
self.master.mainloop()
def create_labels(self, num):
self.picture = Image.open("blue.gif")
self.picture.thumbnail((130,130))
self.tkim = ImageTk.PhotoImage(self.picture)
for label in self.lists_labels:
label.destroy()
self.lists_labels=[]
for i in range(num):
but = tk.Button(self.master, image = self.tkim)
but.grid(row = i + 1, column = 0)
self.lists_labels.append(but)
myapp = Halabala()
This is the code relevant for your question:
class Halabala():
def __init__(self):
.............
self.pictures = ["pavuk1", "pavuk2", "pavuk3"]
self.lists_labels = []
self.lists_images = []
self.init_image_list()
............
def init_image_list(self):
for i in self.pictures:
picture = Image.open(i)
picture.thumbnail((130, 130))
self.lists_images.append(ImageTk.PhotoImage(picture))
def create_labels(self, num):
for label in self.lists_labels:
label.destroy()
self.lists_labels=[]
for i in range(num):
but = tk.Button(self.master, image = self.lists_images[i])
but.grid(row = i + 1, column = 0)
self.lists_labels.append(but)

Making a function run code

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

Categories

Resources