from pubnub import Pubnub ;
from tkinter import *
Window = Tk()
pubnub = Pubnub(publish_key="pub-c-9997b5b1-da6f-4935-88f7-4d0645bcdf2b",
subscribe_key="sub-c-2bc2a578-776c-11e6-9195-02ee2ddab7fe")
def Callback(message, channel):
Logic.UpdateMessageList(message)
Logic.UpdateMessageDisplay()
Display.DisplayMessage()
def Error(message):
Window.title("PubNub - Error")
def Connect(message):
Window.title("PubNub - Connected")
def Reconnect(message):
Window.title("PubNub - Reconnected")
def Disconnect(message):
Window.title("PubNub - Disconnected")
def SendMessage(event):
message = (Logic.Username, Display.MessageEntry.get())
pubnub.publish("my_channel", message = message)
pubnub.subscribe(channels='my_channel',
callback = Callback,
error = Error,
connect = Connect,
reconnect = Reconnect,
disconnect = Disconnect)
class Logic:
def __init__(self):
self.Username = ""
self.MessageList = ([],[])
self.MessageNumber = 0
self.MaxMessages = 6
def UpdateMessageList(self, message):
self.MessageList[0].append(message[0])
self.MessageList[1].append(message[1])
self.MessageNumber += 1
def UpdateMessageDisplay(self):
self.DisplayList = []
if self.MessageNumber >= (self.MaxMessages + 1):
self.MessageList[0].pop(0)
self.MessageList[1].pop(0)
for Num in range(len(self.MessageList[0])):
for ListNum in range(2):
self.DisplayList.append((self.MessageList[ListNum][Num]))
self.DisplayList.append("\n")
Logic = Logic()
class MainDisplay:
def __init__(self):
Window.geometry("400x400")
Window.resizable(0,0)
self.MessageVar = StringVar()
Window.title("PubNub")
def ScreenOne(self):
Window.bind("<Return>", self.AdvScreenTwo)
self.EasyFrame = Frame(Window)
self.EasyFrame.config(bg = "Grey", height = 400, width = 400)
self.EasyFrame.grid()
self.EasyFrame.place(relx = 0.5, y = 200, anchor = CENTER)
self.UsernameEntry = Entry(self.EasyFrame)
self.UsernameEntry.config(width = 15, bg = "White", fg = "Black")
self.UsernameEntry.grid()
self.UsernameEntry.place(relx = 0.5, y = 200, anchor = CENTER)
UsernameLabel = Label(self.EasyFrame, text = "Enter Username")
UsernameLabel.config(bg = "Grey", bd = 0, font = ("times",13,"bold"), fg = "White")
UsernameLabel.grid()
UsernameLabel.place(relx = 0.5, y = 90, anchor = CENTER)
def AdvScreenTwo(self, event):
Logic.Username = (self.UsernameEntry.get())
Window.unbind("<Return>")
self.EasyFrame.grid_forget()
self.EasyFrame.destroy()
Window.bind("<Return>", SendMessage)
self.ScreenTwo()
def ScreenTwo(self):
self.MessagesParent = Frame(Window)
self.MessagesParent.config(bg = "Grey", height = 400, width = 400)
self.MessagesParent.grid()
self.MessagesParent.place(relx = 0.5, y = 200, anchor = CENTER)
self.MessageEntry = Entry(self.MessagesParent)
self.MessageEntry.config(width = 40, bg = "Grey", fg = "Black")
self.MessageEntry.grid()
self.MessageEntry.place(relx = 0.5, y = 350, anchor = CENTER)
def DisplayMessage(self):
Y = 10
for Item in (Logic.MessageList[0]):
self.TextLabel = Label(Window, text = Item, height = 3, width = 6, font = ("times", 8, "bold"), anchor = "w")
self.TextLabel.grid()
self.TextLabel.place(relx = 0.05, y = Y)
Y += 50
Y = 10
for Item in (Logic.MessageList[1]):
self.TextLabel = Label(Window, text = Item, height = 3, width = 40, font = ("times", 8, "bold"),wraplength = 270, anchor = "w")
self.TextLabel.grid()
self.TextLabel.place(relx = 0.2, y = Y)
Y += 50
Display = MainDisplay()
def Main():
Display.ScreenOne()
if __name__ == "__main__":
Main()
Window.mainloop()
This is my code which does work when i run it through the console or IDLE which is fine and all but i would like to compile it. I managed to compile it with my usual method using cx_freeze but i get a error message:
OsError: Cannot load native module 'Cryptodome.Cipher,_raw_ecb'
Can provide any additional information that may be required.
Has gotten a fair amount of views so i thought i would post the answer, i emailed pubnub support
Hi Joshua,
Please use this branch from our SDK https://github.com/pubnub/python/tree/reduce_crypto ; it has cryto unbundled from the dependencies.
This fixed it :) (Replace the pubnub file in Pythonx.x with the pubnub.py file on the git)
Related
I'm trying to run a GUI on a separate process from my "main" program while still being able to retrieve values from the GUI in the "main" module.
Right now I have a simple GUI setup with a simple function on the "main" module to get several values triggered by a button press.
I have instantiated both classes in my "main" module but after I start the GUI process, press the 'start' button to trigger my retrieve & print function I receive the following error:
NameError: name 'start' is not defined
"main" module:
#############################
#### Importing Libraries ####
#############################
from GUI import *
#############################
#### Creating Main Class ####
#############################
class Round_Sling_Main:
def sling_start(self):
current_length = start.get_length()
current_speed = start.get_speed()
current_color = start.get_color()
print(current_length, current_speed, current_color)
if __name__ == "__main__":
round_sling = Round_Sling_Main()
start = GUI(round_sling, 0, 0, "").start()
GUI module:
#############################
#### Importing Libraries ####
#############################
import tkinter as tk
from tkinter import ttk
import sys
from multiprocessing import Process
############################
#### Creating Front GUI ####
############################
class GUI(Process):
def __init__(self, round_sling, length, speed, color):
super(GUI, self).__init__()
self.round_sling = round_sling
self.length = length
self.speed = speed
self.color = color
self.create_GUI()
def retrieve_length(self, length):
self.length = length
def retrieve_speed(self, speed):
self.speed = speed
def retrieve_color(self, event = None):
self.color = event.widget.get()
def get_length(self):
return self.length
def get_speed(self):
return self.speed
def get_color(self):
return self.color
def close(self):
sys.exit()
def create_GUI(self):
while(1):
front = tk.Tk()
front.title ("Round Sling Machine")
front.geometry ('800x600')
#front.config (cursor = 'none')
#front.attributes ("-fullscreen", True)
# Color Selection Label
Color_Label = tk.Label (front, text = 'Select a Sling Color', font = 'Verdana 12')
Color_Label.place(x = 300, y = 0)
# Material Selection Label
Material_Label = tk.Label (front, text = 'Select a Sling Material', font = 'Verdana 12')
Material_Label.place(x = 300, y = 80)
# Length Entry Label
Length_Label = tk.Label (front, text = 'Select Desired Sling Length (inches)', font = 'Verdana 12')
Length_Label.place(x = 240,y = 160)
# Speed Factor Label
Speed_Label = tk.Label (front, text = 'Enter Motor Speed Factor (0.0 - 1.0)', font = 'Verdana 8')
Speed_Label.place(x = 25, y = 35)
# Color Selection Combo Box
ColorVar = tk.StringVar()
SlingColor = ttk.Combobox(front, width = 27, textvariable = ColorVar)
SlingColor['values'] = ('Purple',
'Green',
'Yellow',
'Tan',
'Red',
'White',
'Blue',
'Orange 1',
'Orange 2',
'Orange 3',
'Orange 4',
'Orange 5',
'Orange 6')
SlingColor.state(["readonly"])
SlingColor.place(x = 300, y = 30)
SlingColor.bind("<<ComboboxSelected>>", self.retrieve_color)
# Material Selection Combo Box
MaterialVar = tk.StringVar()
MaterialSel = ttk.Combobox(front, width = 27, textvariable = MaterialVar)
MaterialSel['values'] = ('Nylon', 'Polyester', 'Carbon Fiber')
MaterialSel.state(["readonly"])
MaterialSel.place(x = 300, y = 110)
# Sling Length Slider
SlingLength = tk.Scale(front, from_ = 0, to = 100, length = 600, orient=tk.HORIZONTAL, command = self.retrieve_length)
SlingLength.place(x = 105, y = 190)
# Motor Speed Factor Slider
MotorSpeed = tk.Scale(front, from_ = 0, to = 1.0, resolution = 0.1, length = 200, orient=tk.HORIZONTAL, command = self.retrieve_speed)
MotorSpeed.place(x = 25, y = 50)
startBtn = tk.Button(front, text = 'Start', font = 'Verdana 12', command = self.round_sling.sling_start)
startBtn.place(x = 250, y = 250)
closeBtn = tk.Button(front, text = 'Close', font = 'Verdana 12', command = self.close)
closeBtn.place(x = 450, y = 250)
front.mainloop()
############################
##### End of Front GUI #####
############################
In the ShowMoneyButton class, I want the activation function to only activate if self.button_activated is False, and I set it as False when the SongButton class's activation function is triggered, yet it's not registering. It stays True. Is there a way I can make it so the ShowMoneyButton class's activation function is executed only if the SongButton class's activation function is executed, except for the first time?
import tkinter as tk, random, subprocess, time, os, datetime, pprint
class Song:
def __init__(self):
self.files = []
self.path = "/users/eliasrahoui/desktop/songy"
for filename in os.listdir(self.path):
self.files.append(self.path + "/" + filename)
class Money_Value:
def __init__(self):
with open("money_counter.txt", "r") as f:
a = f.read()
a = int(a)
self.current_value = a
class Clock:
def __init__(self, root):
money = Money_Value()
self.money = money.current_value
self.root = root
self.label = tk.Label(self.root, text = "$" + str(self.money), foreground = "green", font = ('calibri', 100, 'bold'))
self.label.pack()
def countup(self, *args):
root = self.root
money_per_hour = 1000
self.money += 1
self.label['text'] = "$" + str(self.money)
self.root_id = root.after(money_per_hour, self.countup)
def stop(self):
root = self.root
root.after_cancel(self.root_id)
with open("money_counter.txt", "w") as f:
f.write(str(self.money))
def save(self):
with open("money_counter.txt", "w") as f:
f.write(str(self.money))
self.root.destroy()
class Button:
all_buttons = {}
windows = []
return_code = []
button_activated = False
def __init__(self, root, text, command):
self.text = text
button = tk.Button(root, text = text, command = command)
self.all_buttons[self.text] = button
def remove(self, button):
button.pack_forget()
def show_button(self, button):
button.pack(side ="bottom")
class SongButton(Button):
def __init__(self, root, clock):
self.root = root
self.root_clock = clock
super().__init__(self.root, text = "stop song", command = self.activation)
def activation(self):
windows = self.windows
for i in windows:
i.destroy()
code = self.return_code[-1]
code.kill()
self.remove(self.all_buttons["stop song"])
self.root_clock.countup()
self.button_activated = False
class ShowMoneyButton(Button):
def __init__(self, root, clock):
self.root = root
super().__init__(self.root, "show me the money", self.activation)
song = Song()
self.songs = song.files
money_show_button = self.all_buttons["show me the money"]
self.show_button(money_show_button)
self.pic = tk.PhotoImage(file = "/users/eliasrahoui/desktop/IMG_7465.png")
#self.button_activated = False
self.label = tk.Label(self.root, text = "")
self.root_clock = clock
def activation(self):
if self.button_activated == False:
self.root_clock.stop()
num = Money_Value()
money = num.current_value
self.label.config(text =f'Money {money}')
self.label.pack()
random_song = random.choice(self.songs)
a = SongButton(self.root, self.root_clock)
return_cod = subprocess.Popen(["afplay", random_song])
self.return_code.append(return_cod)
self.show_button(self.all_buttons["stop song"])
self.button_activated = True
for _ in range(30):
root = self.root
window = tk.Toplevel(self.root)
self.windows.append(window)
window.minsize(100, 100)
window_label = tk.Label(window, image = self.pic)
window_label.pack()
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = random.randint(0, ws)
y = random.randint(0, hs)
w = 200
h = 200
window.geometry('%dx%d+%d+%d' % (w, h, x, y))
class Timer(Button):
def __init__(self, root, start_time, name, counter = False):
self.count_down_start_time = start_time
self.root = root
self.name = name
self.counter = counter
self.tmp_counter = counter
super().__init__(self.root, text = name, command = self.timer_window)
self.show_button(self.all_buttons[self.name])
self.timer_id = None
self.window_label = None
self.orignial = start_time
self.window = None
self.current_question = 1
self.questions_answered = {}
self.times = [self.orignial]
self.positive = False
self.min_max = {}
def timer_window(self):
self.window = tk.Toplevel(self.root)
self.window.geometry('%dx%d+%d+%d' % (300, 200, 500, 300))
self.window_label = tk.Label(self.window, text = "", font = ('calibri', 100, 'bold'))
self.counter_label = tk.Label(self.window, text = f'Current Question: {self.current_question}')
self.window_label.pack()
self.timer()
def timer(self):
mins, secs = divmod(self.count_down_start_time, 60)
mins = abs(mins)
secs = abs(secs)
timerr = '{:02d}:{:02d}'.format(mins, secs)
if self.count_down_start_time == -1:
self.positive = True
self.window_label["foreground"] = "red"
if self.positive:
self.count_down_start_time += 1
else:
self.count_down_start_time -= 1
self.window_label["text"] = timerr
self.window.protocol("WM_DELETE_WINDOW", self.callback)
if self.counter == True:
button = tk.Button(self.window, text = "Question Done!", command = self.counter_func)
button.pack(side = "bottom")
button_report = tk.Button(self.window, text = "Report", command = self.report)
self.counter = False
self.counter_label.pack()
button_report.pack(side = "bottom")
self.timer_id = self.window.after(1000, self.timer)
def callback(self):
self.window.after_cancel(self.timer_id)
self.window.destroy()
self.count_down_start_time = self.orignial
if self.tmp_counter == True:
self.counter = True
self.current_question = 1
self.questions_answered = {}
self.positive = False
self.times = [self.orignial]
def counter_func(self):
self.questions_answered[self.current_question] = str(datetime.timedelta(seconds = self.times[-1] - self.count_down_start_time))
self.times.append(self.count_down_start_time)
self.current_question += 1
self.counter_label["text"] = f'Current Question: {self.current_question}'
def report(self):
vals = self.times_min_max()
new_window = tk.Toplevel(self.window)
new_window.minsize(300,300)
a = self.questions_answered[1]
data_pretty = pprint.pformat(self.questions_answered)
label = tk.Label(new_window, text = data_pretty)
label.pack()
mx = {f'Maximum time took per question: {vals[0]} question numbers': vals[2]}
mn = {f'Minimum time took per question: {vals[1]} question numbers': vals[-1]}
mx_label = tk.Label(new_window, text = mx, font = ('calibri', 14, 'bold'))
mn_label = tk.Label(new_window, text = mn, font = ('calibri', 14, 'bold'))
mn_label.pack(side = "bottom")
mx_label.pack(side = "bottom")
def times_min_max(self):
f = {}
big = []
small = []
for i in range(1, len(self.questions_answered) + 1):
val = self.questions_answered[i]
if ":" in val:
q = val.split(":")
secs = int(q[-1])
mins = q[0]
secs = secs/60
secs = str(secs)
secs = secs.split(".")
secs = secs[-1]
final = mins + "." + secs
final = (float(final)) * 60
final = round(final)
f[i] = final
else:
f[i] = int(val)
max_val = max(f, key = f.get) #max(f.items(), key=operator.itemgetter(1))[0]
min_val = min(f, key=f.get)#min(f.keys(), key=(lambda key: f[key]))#min(f.items(), key = operator.intemgetter(1))[0]
min_val = f[min_val]
max_val = f[max_val]
for i in f.keys():
if f[i] == max_val:
big.append(i)
if f[i] == min_val:
small.append(i)
return (self.questions_answered[big[0]], self.questions_answered[small[0]], big, small)
main function:
import clocky_classy as cm
import tkinter as tk
root = tk.Tk()
root.minsize(400,200)
my_clock = cm.Clock(root)
money_button = cm.ShowMoneyButton(root, my_clock)
root.protocol("WM_DELETE_WINDOW", my_clock.save)
timer = cm.Timer(root, 120, "2 min timer")
timer = cm.Timer(root, 1800, "30 min timer", counter = True)
my_clock.countup()
root.mainloop()
I need to clear window before I load a new map. But menu buttons have to stay. I was trying self.frame.destroy(), but it kill my menu buttons too. Basically I need to clear class Sokoban, but this class is not in class Window. Problem is in def map1(self): and def map2(self):
import tkinter
from tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('Sokoban')
self.pack(fill = BOTH, expand = 1)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Mapa1', command = self.map1)
menu.add_cascade(label='Mapy', menu=file)
edit = Menu(menu)
edit.add_command(label='Mapa2', command = self.map2)
menu.add_cascade(label='Edit', menu=edit)
def map1(self):
self.frame.forget()
Sokoban('map1.txt')
def map2(self):
self.frame.forget()
Sokoban('map2.txt')
class Sokoban:
def __init__(self, subor):
t = open(subor, 'r')
self.pole = [None] * 8
self.box = []
for a in range(8):
self.pole[a] = list(t.readline().strip())
for b in range(len(self.pole[a])):
if self.pole[a][b] == '$':
self.player = Player(a,b)
self.pole[a][b] = '.'
if self.pole[a][b] == '#':
self.box.append(Box(a,b))
self.pole[a][b] = '.'
t.close()
self.game = self.g = tkinter.Canvas(bg = 'white', width = 650, height = 240,
cursor = 'cross')
self.g.pack()
self.farba = [['gray'],['khaki'],['#FF4500'],['yellow'],['brown']]
stena = '*'
policko = '.'
player = '$'
box = '#'
ciel = '+'
## self.newButt = self.g.create_rectangle(511, 0, 650, 45, fill = 'red')
## self.newButtText = self.g.create_text(580.5, 22.5, text = 'New Game',
## font = 'arial 19 italic bold',
## fill = 'yellow')
## self.map1Butt = self.g.create_rectangle(511, 46, 650, 86, fill = 'red')
## self.map1ButtText = self.g.create_text(580.5, 66, text = 'Map - 1',
## font = 'arial 19 italic bold',
## fill = 'yellow')
## self.map2Butt = self.g.create_rectangle(511, 87, 650, 127, fill = 'red')
## self.map2ButtText = self.g.create_text(580.5, 109, text = 'Map - 2',
## font = 'arial 19 italic bold',
## fill = 'yellow')
## self.map3Butt = self.g.create_rectangle(511, 128, 650, 168, fill = 'red')
## self.map3ButtText = self.g.create_text(580.5, 148, text = 'Map - 3',
## font = 'arial 19 italic bold',
## fill = 'yellow')
self.kresli()
self.g.bind_all('<Up>', self.up)
self.g.bind_all('<Down>', self.down)
self.g.bind_all('<Left>', self.left)
self.g.bind_all('<Right>', self.right)
## self.g.bind('<1>', self.Buttons)
def up(self, e):
self.move(-1, 0)
def down(self, e):
self.move(1, 0)
def left(self, e):
self.move(0, -1)
def right(self, e):
self.move(0, 1)
## def newGame(self):
## self.game.pack_forget()
## Sokoban()
## def map1(self):
## self.game.pack_forget()
## Sokoban('map1.txt')
##
## def map2(self):
## self.game.pack_forget()
## Sokoban('map2.txt')
## def Buttons(self, e):
## if '<1>' and self.newButt:
## self.newGame()
## if '<1>' and self.map1Butt:
## self.map1()
##
## if '<1>' and self.map2Butt:
## self.map2()
def kresli(self):
for a in range(8):
for b in range(17):
x,y = b*30, a*30
f = self.farba['*.+'.index(self.pole[a][b])]
self.g.create_rectangle(x,y,x+30,y+30,fill=f)
self.player.kresli(self.g, self.farba[3])
for box in self.box:
box.kresli(self.g, self.farba[4])
def setBox(self, r, s):
for a in range(len(self.box)):
if self.box[a].r==r and self.box[a].s==s:
return a
return -1
def move(self, dr, ds):
r = self.player.r + dr
s = self.player.s + ds
if r<0 or r>=8 or s<0 or s>=510 or self.pole[r][s] == '*':
return
c = self.setBox(r, s)
if c >= 0:
rr = r + dr
ss = s + ds
if rr < 0 or rr>=8 or ss<0 or ss>=510 or self.pole[rr][ss] == '*':
return
if self.setBox(rr, ss) >= 0:
return
self.box[c].move(dr, ds)
self.player.move(dr, ds)
for c in self.box:
if self.pole[c.r][c.s] != '+':
return
class Player:
def __init__(self, r, s):
self.r = r
self.s = s
def kresli(self, g, farba):
self.g = g
x,y = self.s*30, self.r*30
self.plr = tkinter.PhotoImage(file='player.png')
self.id1 = g.create_image(x+15, y+15, image = self.plr)
def move(self, dr, ds):
self.r = self.r + dr
self.s = self.s + ds
self.g.move(self.id1, ds*30, dr*30)
class Box:
def __init__(self, r, s):
self.r = r
self.s = s
def kresli(self, g, farba):
self.g = g
x,y = self.s*30, self.r*30
self.bx = tkinter.PhotoImage(file='box.png')
self.id2 = g.create_image(x+15, y+15, image = self.bx)
def move(self, dr, ds):
self.r = self.r + dr
self.s = self.s + ds
self.g.move(self.id2, ds*30, dr*30)
root = Tk()
root.geometry('510x240')
app = Window(root)
root.mainloop()
Sokoban()
That not-working wall of code is very hard to work with so I will try to answer your menu buttons have to stay part with an example code.
Basically you create two frames, one holds widgets going to be cleared and second one holds other widgets plus first frame.
import tkinter as tk
root = tk.Tk()
root.geometry("300x300")
frame1 = tk.Frame(root)
frame2 = tk.Frame(frame1)
frame1.pack()
frame2.pack()
menubar = tk.Menu(frame1)
menubar.add_command(label="Bring Back!", command=frame2.pack)
menubar.add_command(label="Quit!", command=root.destroy)
tk.Button(frame2, text="Forget only frame2", command=frame2.pack_forget).pack()
tk.Label(frame2, text="Label on frame2").pack()
root.config(menu=menubar)
root.mainloop()
i'm taking the image from the user, and displaying it using label. Now i have to use that image for further processing.
my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections 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)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def query():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 850, y = 5)
custName.set(path)
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
dis_list1 = list()
imge = cv2.imread(tkimage)
arr = array(imge)
g_img = cv2.imread(tkimage,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(tkimage, 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)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 25, x = 100, width = 500, height = 25)
button1 = Button(app, text='Select the Query Image',command = query)
button1.pack(padx = 2, pady = 2,anchor='ne')
button1.place( x = 550, y = 25)
root.mainloop()
but its giving me an error like:
imge = cv2.imread(tkimage)
TypeError: expected string or Unicode object, instance found
how to overcome this error??
thanks for your support!
You are giving cv2.imread a PhotoImage instance, but it expects a filename. Give it path instead.
imge = cv2.imread(path)
Ok so I'm supposed to make a basic calculator using GUI in python. I completed that task with all buttons working. Now for step 2, I'm supposed to inherit the original calculator class and create a new class called BetterCalculator, which adds in the buttons sqrt, log, pct, and pow. I have got everything working except for the pow button and when I run the program with what the teacher calls a driver, I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "E:\calculator\Calculator in class\calculator.py", line 102, in do3
self.n.set(self.n.get()+'3')
TypeError: 'str' object is not callable
and here is my code:
#Windows basic built-in interface library.
import tkinter
import math
class Calculator:
def __init__(self):
self.win = tkinter.Tk() # Window object created
# Create frames for buttons. Win frame, topFrame(label, display) \
# bottomFrame (numberFrame
self.topFrame = tkinter.Frame(self.win)
self.bottomFrame = tkinter.Frame(self.win)
self.numbersFrame = tkinter.Frame(self.bottomFrame)
self.no123Frame = tkinter.Frame(self.numbersFrame)
self.no456Frame = tkinter.Frame(self.numbersFrame)
self.no789Frame = tkinter.Frame(self.numbersFrame)
self.no0DFrame = tkinter.Frame(self.numbersFrame)
self.optsFrame = tkinter.Frame(self.bottomFrame)
# Create object Label to use for input and output. StringVar is a class.
self.n = tkinter.StringVar()
# Display object created
self.display = tkinter.Label(self.topFrame, textvariable = self.n, bg = 'white', font = 12, height = 2, width = 20)
# Number Buttons created. self.b1 = object, tkinter.button calls button module, command = do1 will\
# become a method.
self.b1 = tkinter.Button(self.no123Frame, width = 3 , text = '1', command = self.do1)
self.b2 = tkinter.Button(self.no123Frame, width = 3 , text = '2', command = self.do2)
self.b3 = tkinter.Button(self.no123Frame, width = 3 , text = '3', command = self.do3)
self.b4 = tkinter.Button(self.no456Frame, width = 3 , text = '4', command = self.do4)
self.b5 = tkinter.Button(self.no456Frame, width = 3 , text = '5', command = self.do5)
self.b6 = tkinter.Button(self.no456Frame, width = 3 , text = '6', command = self.do6)
self.b7 = tkinter.Button(self.no789Frame, width = 3 , text = '7', command = self.do7)
self.b8 = tkinter.Button(self.no789Frame, width = 3 , text = '8', command = self.do8)
self.b9 = tkinter.Button(self.no789Frame, width = 3 , text = '9', command = self.do9)
self.b0 = tkinter.Button(self.no0DFrame, width = 3 , text = '0', command = self.do0)
self.bD = tkinter.Button(self.no0DFrame, width = 3 , text = '.', command = self.doD)
self.bCal = tkinter.Button(self.no0DFrame, width = 3 , text = '=', command = self.cal)
# Operators created
self.bAdd = tkinter.Button(self.optsFrame, width = 5, text = '+', command = self.add)
self.bSub = tkinter.Button(self.optsFrame, width = 5, text = '-', command = self.sub)
self.bMul = tkinter.Button(self.optsFrame, width = 5, text = '*', command = self.mul)
self.bDiv = tkinter.Button(self.optsFrame, width = 5, text = '/', command = self.div)
self.bMod = tkinter.Button(self.optsFrame, width = 5, text = '%', command = self.mod)
self.bClr = tkinter.Button(self.topFrame, width = 5, text = 'Clear', command = self.clr)
# Create numbers. op1 = operand, op2 = operator
op1 = 0.0
op2 = 0.0
opt = ''
def organizeInterface(self):
# Method pack object(assembling display label into window).
# Order of packing will be the order the labels will display.
self.display.pack(side = 'left')
self.bClr.pack()
self.topFrame.pack()
self.b1.pack(side = 'left')
self.b2.pack(side = 'left')
self.b3.pack(side = 'left')
self.no123Frame.pack()
self.b4.pack(side = 'left')
self.b5.pack(side = 'left')
self.b6.pack(side = 'left')
self.no456Frame.pack()
self.b7.pack(side = 'left')
self.b8.pack(side = 'left')
self.b9.pack(side = 'left')
self.no789Frame.pack()
self.bD.pack(side = 'left')
self.b0.pack(side = 'left')
self.bCal.pack(side = 'left')
self.no0DFrame.pack(side = 'left')
self.numbersFrame.pack(side = 'left')
self.bAdd.pack(side = 'left')
self.bSub.pack(side = 'left')
self.bDiv.pack(side = 'left')
self.bMul.pack(side = 'left')
self.bMod.pack(side = 'left')
self.optsFrame.pack()
self.bottomFrame.pack()
def runInterface(self):
tkinter.mainloop()
#clear user input.
def clear(self):
self.op1 = 0.0
self.op2 = 0.0
self.opt = ''
# Set user input, set variable self.n.set then self.n.get will append and concatonate.
def do1(self):
self.n.set(self.n.get()+'1')
def do2(self):
self.n.set(self.n.get()+'2')
def do3(self):
self.n.set(self.n.get()+'3')
def do4(self):
self.n.set(self.n.get()+'4')
def do5(self):
self.n.set(self.n.get()+'5')
def do6(self):
self.n.set(self.n.get()+'6')
def do7(self):
self.n.set(self.n.get()+'7')
def do8(self):
self.n.set(self.n.get()+'8')
def do9(self):
self.n.set(self.n.get()+'9')
def do0(self):
self.n.set(self.n.get()+'0')
def doD(self):
self.n.set(self.n.get()+'.')
# record operator = self.opt and get first number entry = self.n.get().
# need to clean up the label of the first number entry before getting next \
# entry of numbers.
def add(self):
self.opt = '+'
self.op1 = float(self.n.get())
self.n.set('')
#to get calculator to see negative number verse \
#subtraction create if statement for empty string.
def sub(self):
if self.n.get() == '':
self.n.set('-')
else:
self.opt = '-'
self.op1 = float(self.n.get())
self.n.set('')
def mul(self):
self.opt = '*'
self.op1 = float(self.n.get())
self.n.set('')
def div(self):
self.opt = '/'
self.op1 = float(self.n.get())
self.n.set('')
def mod(self):
self.opt = '%'
self.op1 = float(self.n.get())
self.n.set('')
# clear set to clr button to clean label
def clr(self):
self.clear()
self.n.set('')
# Call calculate method to get calculations and write if statements \
# to define what operator user wanted.
def cal(self):
self.op2 = float(self.n.get())
if self.opt == '+':
self.n.set(self.op1 + self.op2)
elif self.opt == '-':
self.n.set(self.op1 - self.op2)
elif self.opt == '*':
self.n.set(self.op1 * self.op2)
elif self.opt == '/':
self.n.set(self.op1 / self.op2)
elif self.opt == '%':
self.n.set(self.op1 % self.op2)
class BetterCalculator(Calculator):
def __init__(self):
Calculator.__init__(self)
self.uOptsFrame = tkinter.Frame(self.bottomFrame)
self.bLog = tkinter.Button(self.uOptsFrame, width = 5, text = 'log', command = self.log)
self.bPct = tkinter.Button(self.uOptsFrame, width = 5, text = 'Pct', command = self.pct)
self.bSqrt = tkinter.Button(self.uOptsFrame, width = 5, text = 'Sqrt', command = self.sqrt)
self.bPow = tkinter.Button(self.optsFrame, width = 5, text = 'pow', command = self.pow)
def reorganizeInterface(self):
self.bClr.configure(bg = 'red')
self.bAdd.configure(bg = 'yellow')
self.bSub.configure(bg = 'yellow')
self.bMul.configure(bg = 'yellow')
self.bDiv.configure(bg = 'yellow')
self.bMod.configure(bg = 'yellow')
self.bCal.configure(bg = 'green')
Calculator.organizeInterface(self)
self.bLog.pack()
self.bPct.pack()
self.bSqrt.pack()
self.bPow.pack()
self.uOptsFrame.pack(side='left')
def log(self):
self.op1 = float(self.n.get())
self.n.set(math.log(self.op1))
def pct(self):
self.op1 = float(self.n.get())
self.n.set(self.op1 * 100)
def sqrt(self):
self.op1 = float(self.n.get())
self.n.set(math.sqrt(self.op1))
def pow(self):
self.opt = 'pow'
self.op1 = float(self.n.get())
self.n.set = ('')
def cal(self):
Calculator.cal(self)
if self.opt == 'pow':
self.n.set(self.op1 ** self.op2)
this is a separate file for the driver of this program to make it run:
import calculator
import math
def main():
myCal = calculator.BetterCalculator()
myCal.reorganizeInterface()
myCal.runInterface()
main()
Without looking at the rest of the code, I see an obvious typo / brain-o in pow:
def pow(self):
self.opt = 'pow'
self.op1 = float(self.n.get())
self.n.set = ('')
That last line should be:
self.n.set('')
without the = part, so as to call self.n.set, not to replace the function with a string. (Replacing the function with a string will cause a later attempt to call self.n.set to produce the error you saw.)
Look at your pow() method
self.n.set = ('')
It's definitely is a typo. Replace with
self.n.set('')