I want to display the values in the text boxes, but i'm getting this error:
blue.set(B_mean1)
AttributeError: 'numpy.ndarray' object has no attribute 'set'
and my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections import *
from CBIR import *
from experiment import *
from scipy.spatial import distance
import Tkinter,tkFileDialog
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent,background="light grey")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
custName.set(path)
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 100, y = 100)
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
dis_list1 = list()
imge = cv2.imread(path)
arr = array(imge)
g_img = cv2.imread(path,0)
gray_re_img = cv2.resize(g_img,(256,256))
graylist1.append(gray_re_img)
equ = cv2.equalizeHist(gray_re_img)
eq_graylist1.append(equ)
re_img = cv2.resize(imge,(256,256))
resizelist1.append(re_img)
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
im = skimage.io.imread(path, as_grey=True)
im = skimage.img_as_ubyte(im)
im /= 32
g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
cont_list1.append(cont)
ene = skimage.feature.greycoprops(g, 'energy')[0][0]
ene_list1.append(ene)
homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
homo_list1.append(homo)
cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
cor_list1.append(cor)
dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
dis_list1.append(dis)
feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
blue.set(B_mean1)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
label = Label(app, text='Python Image Search', fg = 'black',font = 'PoorRichard 24')
label.pack()
label.place(y = 5, x = 0)
img = Image.open('logo.png')
bg_img = ImageTk.PhotoImage(img)
label1 = Label(app, image = bg_img)
label1.place(y = 5, x = 1225)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.grid(column=0,row=0,sticky='EW')
yourName.update()
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 60, x = 100, width = 525, height = 25)
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar()
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
All I want to know is how to display the values into the textbox. Any suggestions are welcome.
Thanks in advance!
Your problem is that you are using the variable name blue for two different things. At one point it's a numpy array and at another it is an IntVar. When you call blue.set(...), you are doing that at the point where blue references a numpy array, hence the error message 'numpy.ndarray' object has no attribute 'set'
Try changing the name of your IntVar to something else, such as blue_var, and make sure you change it everywhere.
Related
I am trying to put an image into a window with ImageTk and PhotoImage. Below is the code:
import tkinter as tk
import random as r
from PIL import ImageTk, Image
window = tk.Tk()
HEIGHT = window.winfo_screenwidth()
WIDTH = window.winfo_screenheight()
RESOL = str(str(HEIGHT) + "x" + str(WIDTH+7) + "+" + str(-7) + "+" + str(0))
window.geometry(RESOL)
x = int(HEIGHT)/2
y = int(WIDTH)/2
updatex = HEIGHT + (0.6 * HEIGHT)
main = tk.Frame(window, height = WIDTH, width = HEIGHT)
main.configure(bg = "white", highlightthickness = 0)
main.place(x = x, y = y, anchor = "center")
Map = tk.Canvas(window, height = int((900 - int(x))) + int(900), width = int((900 - int(y))) + int(900), bg = "#44b863", highlightthickness = 0)
Map.place(x = updatex, y = int(y), anchor = "center")
p = tk.PhotoImage(file = "TitleForGameReal.png")
play_solo_image = tk.PhotoImage(file = "PlaySoloButton.png")
play_duo_image = tk.PhotoImage(file = "PlayDuoButton.png")
title = tk.Label(main, image = p, highlightthickness = 0, bd = 0)
title.place(relx = 0.5, rely = 0.35, anchor = "center")
class CustomButton:
def __init__(self, image, master, height, width, bordercolor):
self.master = master
self.frame = tk.Frame(master, height = height, width = width, highlightthickness = 0)
self.image = tk.Label(self.frame, image = image, borderwidth = 0, bg = "dark grey")
self.bordercolor = bordercolor
def put(self, x, y, command):
self.x, self.y = x, y
self.frame.place(relx = x, rely = y, anchor = "center")
self.image.pack()
def enter(event = "<Enter>"):
self.image.config(borderwidth = 3)
self.image.bind("<Enter>", enter)
def leave(event = "<Leave>"):
self.image.config(borderwidth = 0)
self.image.bind("<Leave>", leave)
def bind_command(event = "<Button-1>"):
command()
self.image.bind("<Button -1>", bind_command)
def solo():
global x, y, updatex
for i in range(int(int(int(HEIGHT/9))/2)):
x -= 20
updatex -= 20
main.place(x = x, y = y, anchor = "center")
Map.place(x = updatex, y = y, anchor = "center")
main.update()
Map.update()
player_image = Image.open("Connector.png")
player_image2 = ImageTk.PhotoImage(player_image)
class Player:
def __init__(self, hp, image):
self.hp = hp
self.image = tk.Label(Map, image = image)
self.image.place(relx = 0.5, rely = 0.5, anchor = "center")
def spawn(self):
Map.create_image(updatex, y, image = self.image)
player = Player(100, player_image2)
player.spawn()
def duo():
print("duo")
play_solo_image = tk.PhotoImage(file = "PlaySoloButton.png")
play_solo_button = CustomButton(image = play_solo_image, master = main, height = play_solo_image.height(), width = play_solo_image.width(), bordercolor = "grey")
play_solo_button.put(x = 0.39, y = 0.47, command = solo)
play_duo_button = CustomButton(image = play_duo_image, master = main, height = play_duo_image.height(), width = play_duo_image.width(), bordercolor = "grey")
play_duo_button.put(x = 0.61, y = 0.47, command = duo)
I will also leave the image as a reference, because I edited the photo to strictly have a transparent background in PhotoShop:
But this is the output I see:
Later I realized that I was also receiving an error, which may or may not have something to do with my issue:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 125, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python35\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1559, in __call__
return self.func(*args)
File "C:\Users\offcampus\Desktop\New folder\SurvivalGame.py", line 50, in bind_command
command()
File "C:\Users\offcampus\Desktop\New folder\SurvivalGame.py", line 75, in solo
player.spawn()
File "C:\Users\offcampus\Desktop\New folder\SurvivalGame.py", line 73, in spawn
Map.create_image(updatex, y, image = self.image)
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2338, in create_image
return self._create('image', args, kw)
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2329, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image ".2469091717696.2469132063968" doesn't exist
I know this may have something to do with garbage collection, and I would normally save a reference of it, but the problem is I can't do that since it will tell me "you can't pack a PhotoImage".
This is the tutorial I used to make the image background transparent. It's not my video, so don't flag it as spam.
The problem is image option of Map.create_image(updatex, y, image = self.image) requires a PhotoImage instance but you're giving it a label, so to fix it just say.
class Player:
def __init__(self, hp, image):
self.hp = hp
self.image = image #creating an instance variable
self.pic = ImageTk.PhotoImage(self.image) #making an photoimage instance
self.cv = Map.create_image(updatex, y, image = self.pic) #passing the photo image instance
self.pic.image = self.pic #keeping a reference to the image
Hope this has solved the error, do let me know if any errors or doubts.
I am writing a class and within that class I am having a window that will hold certain widgets (labels, buttons and entry-boxes) when i am using the filedialog.askopenfilename the original window gets closed and does not come back. Is there something I can do?
from tkinter import *
from tkinter.ttk import Combobox
from tkinter import filedialog
class Editor():
def __init__(self, master):
# Variablen definieren
self.fname = StringVar()
# Variable belegen
self.master = master
# Screen auf Seitengröße anpassen
b = 700
h = 500
ao = int((self.master.winfo_screenheight() - h) / 2)
al = int((self.master.winfo_screenwidth() - b) / 2)
self.master.geometry("{}x{}+{}+{}".format(b, h, al, ao))
# Fenster Name festlegen
self.master.title('Editor')
# Farbe des Hintergrundes setzen
self.master.configure(bg = "#FFEC8B")
# Erstelle ein Frame
self.n = Frame(self.master, width = 500, height = 320)
# ComboBox Feldnamen
self.cb = Combobox(self.n, width = 25, values = [1, 2, 3])
# Positioniere den Frame
self.n.pack(side = TOP, anchor = NE, padx = 10, pady = 20)
# Positionieren der ComboBox
self.cb.place(x = 20, y = 20)
# Button: Open
self.b16 = Button(self.master, text = "Open", width = 10, command = self.openfile)
self.b16.place(x = 15, y = 360)
def openfile(self):
ftype = [("vcd file", ".vcd")]
title = "Open Filename"
initial = "c:\\users\\ich\\pycharmprojects\\penval\\valdata\\"
self.fname = filedialog.askopenfilename(filetypes = ftype, title = title, initialdir = initial)
def symbol(self, z, a):
return
I am new to Tkinter. I'd like to write simple program and organize it using pack() method. Here is my code:
import Tkinter as tk
from Tkinter import *
import xlrd, os, sys, json
class Main():
def __init__(self):
global col, col1
self.master = tk.Tk()
self.master.title("Zliczanie ilosci spraw")
self.master.minsize(width=800, height=600)
plik = 'Aktualnie wybrany plik to: ' + 'Rejestr'
text = Label(self.master, text = plik)
text.pack(pady = 20)
self.wyswietlanie()
def wyswietlanie(self):
'''Funkcja, ktora zlicza i wyswietla ilosc spraw pracownikow'''
policzone_1 = []
policzone_2 = []
z = 0
dzial1 = {
"Pracownik1": "PRAC1",
"Pracownik2": "PRAC2"}
dzial2 = {
"Pracownik12": "PRAC12",
"Pracownik22": "PRAC22"}
for nazw in dzial1:
x = dzial1[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_1.append((nazw, nazwisko))
for nazw in dzial2:
x = dzial2[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_2.append((nazw, nazwisko))
posortowane1 = sorted(policzone_1,key=lambda x:x[1], reverse=True)
posortowane2 = sorted(policzone_2,key=lambda x:x[1], reverse=True)
dzial3 = Label(self.master)
dzial3.pack(side = LEFT)
dzial4 = Label(self.master)
dzial4.pack(side = LEFT)
for i in posortowane1:
wynik = '%s: %s' % (i[0], i[1])
dzial1 = Label(self.master, text = wynik, font = "Verdana 10 bold")
dzial1.pack(in_ = dzial3, padx = 200)
for i in posortowane2:
wynik = '%s: %s' % (i[0], i[1])
dzial2 = Label(self.master, text = wynik)
dzial2.pack(in_ = dzial4, padx = 200)
def run(self):
self.master.mainloop()
glowne = Main()
glowne.run()
Result is as on image below:
Why dzial1 and dzial2 are in these places (far from "text")? How can I organize dzial1, dzial2 (set them closer to each other)?
from tkinter import *
from random import *
from functools import partial
class Game:
def __init__(self):
self.root = Tk()
self.frame = Frame(width = 574, height = 574)
self.frame.grid(columnspan = 30, rowspan = 30)
self.minex = []
self.miney = []
self.clickx = 0
self.clicky = 0
blank = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\blank.gif')
for i in range(0,30):
for j in range(0,30):
button = Button(width = 15, height = 15, padx = 2, pady = 2, image = blank, command = partial(self.click, j, i))
button.grid(row = i, column = j)
self.mine_place()
self.root.mainloop()
def mine_place(self):
for i in range(0,15):
self.minex.append(randint(1,30))
self.miney.append(randint(1,30))
def click(self, j, i):
miss = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\miss.gif')
hit = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\hit.gif')
for k in range(0, len(self.minex)):
if j + 1 == self.minex[k] and i + 1 == self.miney[k]:
button = Button(image = hit)
button.grid(row = i, column = j)
else:
button = Button(image = miss)
button.grid(row = i, column = j)
app = Game()
In self.click, when I wish to create a button with this image I am given a blank image. If I create a button in init, the image comes out just fine. What is wrong?..............................................................
It looks like you're images are getting garbage collected you need to save a reference to the images after using PhotoImage.
ie - you create the image blank so save a reference as self.blank= blank and use image = self.hit
I'm very new to programming so please excuse me if I lack the correct terminology.
I'm trying to retrieve an image from a website and post it onto a GUI with tkinter. It works, insofar as it posts the image on the GUI; however it still produces an error as per the title of this post.
The section of code that's causing the error is as follows:
raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
image = raw_data("img", ("class", "si"))[0]
image = image["src"]
if image == ("/images/icons/5.gif"):
URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
b64_data = base64.encodestring(URL)
image = PhotoImage(data = b64_data)
label = Label(self, image = image).grid(row = 1, column = 2)
self(image)
Narrowed down further it seems line 39 is causing the error.
self(image)
Full program as follows:
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup
class Weather(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.configure(bg = "#ededed")
self.grid()
self.heading = Label(self, bg = "#ededed", text = " Temperature ").grid(row = 0, column = 1, pady = 5)
self.heading = Label(self, bg = "#ededed", text = " Picture ").grid(row = 0, column = 2, pady = 5)
button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)
self.obsVar1 = StringVar()
label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
self.obsVar1.set("")
def canberra_data(self):
soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
for row in soup("th", {"id" : "obs-station-canberra"}):
for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
self.obsVar1.set(temp.text)
raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
image = raw_data("img", ("class", "si"))[0]
image = image["src"]
if image == ("/images/icons/5.gif"):
URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
b64_data = base64.encodestring(URL)
image = PhotoImage(data = b64_data)
label = Label(self, image = image).grid(row = 1, column = 2)
self(image)
master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()
I should add that if the website has updated its image and it's no longer '5.gif' (being a weather icon it's highly likely) then a picture won't show up.
Any help or direction would be much appreciated. I've looked high and low but to no avail. Thank you in advance.
You cannot call an object like a function. When you say self(image) in your code, you are trying to call the object. If you want to do that you need to implement the __call__ method. However, I have coded your example and made changes to it. Kindly run it. I hope it helps
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup
class Weather(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.configure(bg = "#ededed")
self.grid()
self.heading = Label(self, bg = "#ededed", text = " Temperature ").grid(row = 0, column = 1, pady = 5)
self.heading = Label(self, bg = "#ededed", text = " Picture ").grid(row = 0, column = 2, pady = 5)
button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)
self.obsVar1 = StringVar()
label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
self.obsVar1.set("")
def canberra_data(self):
soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
for row in soup("th", {"id" : "obs-station-canberra"}):
for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
self.obsVar1.set(temp.text)
raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
image = raw_data("img", ("class", "si"))[0]
image = image["src"]
if image == ("/images/icons/5.gif"):
URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
b64_data = base64.encodestring(URL)
image = PhotoImage(data = b64_data)
label = Label(self, image = image)
label.image = image
label.grid(row=1,column=2)
master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()
The diff of your and my version is as follows:
< label = Label(self, image = image).grid(row = 1, column = 2)
< self(image)
---
> label = Label(self, image = image)
> label.image = image
> label.grid(row=1,column=2)
The line containing self(image) is not correct. The 'self' is not a class, it's an object. So, if you want to create an object of type Weather and pass something to its constructor, just call Weather(image).