Python error pop up not working - python-2.7

Writing code and I broke it somehow and can't remember what was previously working, only been using python a few weeks and after working on this literally all day, I'm more than a little frustrated...
# A program to calculate delivery order totals
from graphics import *
#Error Window
def errorWindow():
errwin = GraphWin("Error", 200, 200)
errwin.setCoords(0.0, 0.0, 4.0, 4.0)
errwin.setBackground(color_rgb(33,158,87))
Text(Point(2, 3), "This is not a valid order").draw(errwin)
Text(Point(2, 2.5), "Please try again").draw(errwin)
outline = Rectangle(Point(1.5,1), Point(2.5,2))
outline.setFill('white')
outline.draw(errwin)
okbutton = Text(Point(2,1.5),"OK")
okbutton.draw(errwin)
done=errwin.getMouse()
if (done.getX() > 1.5 and done.getX() < 2.5):
errwin.close()
def main():
win = GraphWin("Brandi's Bagel House", 500, 500)
win.setCoords(0.0, 0.0, 10.0, 10.0)
win.setBackground(color_rgb(33,158,87))
#Banner
banner = Rectangle(Point(0, 8), Point(10, 10))
banner.setFill(color_rgb(97,76,26))
banner.setOutline(color_rgb(97,76,26))
banner.draw(win)
#Logo Image
circ = Circle(Point(1,9), .65)
circ.setFill('white')
circ.setOutline('white')
circ.draw(win)
circ2 = Circle(Point(1,9), .6)
circ2.setFill(color_rgb(33,158,87))
circ2.setOutline(color_rgb(33,158,87))
circ2.draw(win)
bigb = Text(Point(1, 9),"B")
bigb.setStyle('bold italic')
bigb.setTextColor('white')
bigb.setFace('courier')
bigb.setSize(28)
bigb.draw(win)
#Horizontal Lines
Line(Point(0,2.25), Point(10,2.25)).draw(win)
Line(Point(0,4.25), Point(10,4.25)).draw(win)
Line(Point(0,6.25), Point(10,6.25)).draw(win)
#Text
title = Text(Point(4,9), "Delivery Orders:")
title.setSize(20)
title.setTextColor('white')
title.draw(win)
Text(Point(1.5,7), "Bagels:").draw(win)
whitetext = Text(Point(3,7.5), "White")
whitetext.setSize(10)
whitetext.draw(win)
wheattext = Text(Point(5,7.5), "Wheat")
wheattext.setSize(10)
wheattext.draw(win)
Text(Point(1.5,5), "Toppings:").draw(win)
creamtext = Text(Point(3,5.8), "Cream")
creamtext.setSize(10)
creamtext.draw(win)
cheesetext = Text(Point(3,5.5), "Cheese")
cheesetext.setSize(10)
cheesetext.draw(win)
buttertext = Text(Point(5,5.5), "Butter")
buttertext.setSize(10)
buttertext.draw(win)
jellytext = Text(Point(7,5.5), "Jelly")
jellytext.setSize(10)
jellytext.draw(win)
Text(Point(1.5,3), "Coffee:").draw(win)
regtext = Text(Point(3,3.5), "Regular")
regtext.setSize(10)
regtext.draw(win)
decaftext = Text(Point(5,3.5), "Decaf")
decaftext.setSize(10)
decaftext.draw(win)
Text(Point(7,1.5), "Subtotal:").draw(win)
Text(Point(7,1), "Tax:").draw(win)
Text(Point(7,0.5), "Total:").draw(win)
#input bagel
bagel1 = Entry(Point(3,7), 3)
bagel1.setText("0")
bagel1.draw(win)
bagel2 = Entry(Point(5,7), 3)
bagel2.setText("0")
bagel2.draw(win)
#input topping
top1 = Entry(Point(3,5), 3)
top1.setText("0")
top1.draw(win)
top2 = Entry(Point(5,5), 3)
top2.setText("0")
top2.draw(win)
top3 = Entry(Point(7,5), 3)
top3.setText("0")
top3.draw(win)
#input coffee
coff1 = Entry(Point(3,3), 3)
coff1.setText("0")
coff1.draw(win)
coff2 = Entry(Point(5,3), 3)
coff2.setText("0")
coff2.draw(win)
#Calculate Button
outer1 = Rectangle(Point(4.2,0.6), Point(5.8,1.4))
outer1.setFill('white')
outer1.draw(win)
button = Text(Point(5,1),"Calculate")
button.draw(win)
#Quit Buttons
outer2 = Rectangle(Point(9,9.2), Point(9.95,9.95))
outer2.setFill('white')
outer2.draw(win)
button = Text(Point(9.5,9.6),"Quit")
button.draw(win)
#Output
subtotaloutput = Text(Point(9,1.5), "$0.00")
subtotaloutput.draw(win)
taxoutput = Text(Point(9,1), "$0.00")
taxoutput.draw(win)
totaloutput = Text(Point(9,0.5), "$0.00")
totaloutput.draw(win)
#calculations
whitebagel = eval(bagel1.getText())
whitetotal = whitebagel* 1.25
wheatbagel = eval(bagel2.getText())
wheattotal = wheatbagel*1.50
creamcheese = eval(top1.getText())
creamtotal = creamcheese* 0.50
butter = eval(top2.getText())
buttertotal = butter*0.25
jelly = eval(top3.getText())
jellytotal = jelly*0.75
regularcoff = eval(coff1.getText())
regulartotal = regularcoff*1.25
decafcoff = eval(coff2.getText())
decaftotal = decafcoff*1.25
click = win.getMouse()
if (click.getX() > 4.2 and click.getX() < 5.8 and (whitebagel >0 or wheatbagel >0)):
subtotal = whitetotal+wheattotal+creamtotal+buttertotal+jellytotal+regulartotal+decaftotal
tax = .06
taxes = subtotal*tax
total = taxes+subtotal
subtotal = "$%0.2f" % (subtotal)
taxes = "$%0.2f" % (taxes)
total = "$%0.2f" % (total)
subtotaloutput.setText(subtotal)
taxoutput.setText(taxes)
totaloutput.setText(total)
#Coffee Cup Image
bottomoval = Oval(Point(0.7,0.4), Point(1.4, 0.7))
bottomoval.setFill(color_rgb(97,76,26))
bottomoval.setOutline(color_rgb(97,76,26))
bottomoval.draw(win)
cup = Rectangle(Point(0.7,0.5), Point(1.4,1.3))
cup.setFill(color_rgb(97,76,26))
cup.setOutline(color_rgb(97,76,26))
cup.draw(win)
topoval = Oval(Point(0.6,1.2), Point(1.5, 1.5))
topoval.setFill('white')
topoval.setOutline(color_rgb(97,76,26))
topoval.draw(win)
coffee = Oval(Point(0.7,1.26), Point(1.4, 1.45))
coffee.setFill(color_rgb(71,54,14))
coffee.setOutline(color_rgb(71,54,14))
coffee.draw(win)
tinycirc = Circle(Point(1.05,0.8), .3)
tinycirc.setFill(color_rgb(33,158,87))
tinycirc.setOutline('white')
tinycirc.draw(win)
letter = Text(Point(1.05,0.8),"B")
letter.setStyle('bold italic')
letter.setTextColor('white')
letter.setFace('courier')
letter.setSize(17)
letter.draw(win)
#Bagel
outerbagel = Oval(Point(1.8, 0.4), Point(2.7, 1))
outerbagel.setFill(color_rgb(191,157,61))
outerbagel.draw(win)
shadow = Oval(Point(2.1, 0.7), Point(2.4, 0.8))
shadow.setFill(color_rgb(130,102,26))
shadow.draw(win)
elif(click.getX() > 4.2 and click.getX() < 5.8 and whitebagel <1 and wheatbagel <1):
errorWindow()
#End
point = win.getMouse()
if (point.getX() > 9 and point.getX() < 9.95):
win.close()
main()
I need an error window to pop up if bagels are not selected with an order, as for this example coffee and toppings are not available for delivery without bagels. I think I previously had this in a try/except, but now I can't get that to work either. Either it won't calculate the totals and pops up or it calculates but still pops up the error, or nothing happens! I also can't seem to find any direction on after closing the pop up, to go back to a functioning main window. When I do close out the error window, the main window no longer works. I'd like to be able to do that. Lastly I cannot use tkinter, only graphics.py. I also apologize if anything is crudely done, so far it's the only way I know. Thanks in advance for any advice.
I am still hoping someone will take pity on me and give me some direction as to where I'm going wrong with this code... I have changed the part I'm having issues with but it's still not working:
try:
click = win.getMouse()
if click.getX() > 4.2 and click.getX() < 5.8 and whitebagel >0 and wheatbagel >0:
subtotal = whitetotal+wheattotal+creamtotal+buttertotal+jellytotal+regulartotal+decaftotal
tax = .06
taxes = subtotal*tax
total = taxes+subtotal
subtotal = "$%0.2f" % (subtotal)
taxes = "$%0.2f" % (taxes)
total = "$%0.2f" % (total)
subtotaloutput.setText(subtotal)
taxoutput.setText(taxes)
totaloutput.setText(total)
#Coffee Cup Image
bottomoval = Oval(Point(0.7,0.4), Point(1.4, 0.7))
bottomoval.setFill(color_rgb(97,76,26))
bottomoval.setOutline(color_rgb(97,76,26))
bottomoval.draw(win)
cup = Rectangle(Point(0.7,0.5), Point(1.4,1.3))
cup.setFill(color_rgb(97,76,26))
cup.setOutline(color_rgb(97,76,26))
cup.draw(win)
topoval = Oval(Point(0.6,1.2), Point(1.5, 1.5))
topoval.setFill('white')
topoval.setOutline(color_rgb(97,76,26))
topoval.draw(win)
coffee = Oval(Point(0.7,1.26), Point(1.4, 1.45))
coffee.setFill(color_rgb(71,54,14))
coffee.setOutline(color_rgb(71,54,14))
coffee.draw(win)
tinycirc = Circle(Point(1.05,0.8), .3)
tinycirc.setFill(color_rgb(33,158,87))
tinycirc.setOutline('white')
tinycirc.draw(win)
letter = Text(Point(1.05,0.8),"B")
letter.setStyle('bold italic')
letter.setTextColor('white')
letter.setFace('courier')
letter.setSize(17)
letter.draw(win)
#Bagel
outerbagel = Oval(Point(1.8, 0.4), Point(2.7, 1))
outerbagel.setFill(color_rgb(191,157,61))
outerbagel.draw(win)
shadow = Oval(Point(2.1, 0.7), Point(2.4, 0.8))
shadow.setFill(color_rgb(130,102,26))
shadow.draw(win)
except:
errorWindow()
I think i'm losing my mind here with the amount of time I've been trying to get this to work...

First, tkinter is not the way to go with graphics. It is kinda old and a lot of the concepts there will not turn out to be portable. Then again, use it if there is no other option...
Second, the code for ErrorWindow is not properly indented. When it is, I get at least one error popup. Possibly not in the right error condition.
Third, I would put some sort of check for the Y coordinates of the click as well, since you can trigger the Calculate button by clicking anywhere in its vertical column, like say the wheat text box.
Usually with a GUI there is some sort of event loop for processing multiple clicks. Something like:
while(True):
click = win.getMouse()
if calculate button:
get text values
if not bagels:
errorWindow()
continue
calculate
elif quit button:
break
I made a modified version that had an event loop structured this way and I got it to give multiple totals, as well as putting up an error when I had no bagel order and then keeping going.

Related

cv2.VideoCapture freeze framing when using a countdown timer with pressed key 's' for rock paper scissors project

I have defined two different functions, one for getting the prediction of the user using the Teachable Machine from Google and then a countdown function which is initiated by the 'S' key within the loop.
My issue is that when I click the 'S' key my Video Capture freeze frames and begins the countdown, when all I want it to be doing is allowing the user to ready themselves for creating one of three gestures.
The code is below:
def get_user_choice(self):
user_choice = ''
while True:
ret, frame = cap.read()
resized_frame = cv2.resize(frame, (224, 224), interpolation = cv2.INTER_AREA)
image_np = np.array(resized_frame)
normalized_image = (image_np.astype(np.float32) / 127.0) - 1 # Normalize the image
data[0] = normalized_image
prediction = model.predict(data, verbose=0)
cv2.imshow('frame', frame)
k = cv2.waitKey(1)
if k == ord('s'):
countdown()
user_index = np.argmax(prediction[0])
user_choice = user_options[user_index]
print('You chose:', user_choice)
return user_choice
def countdown():
print('Get your answer ready!')
prev = time.time() + 1
TIMER = int(4)
while TIMER >= 1:
cur = time.time()
if cur - prev >= 1:
prev = cur
TIMER = TIMER -1
print(TIMER)
It works almost perfectly apart from the countdown function which has created a freeze frame issue.
I've tried to mess around with the countdown function, and put the videocapture into the countdown function. Nothing seems to have worked for me so far, and thus is causing frustration.

AVAssetExportSession make black video sometimes

I'm new baby for Video Processing use Swift 3. I try to merge multiple videos with AVAssetExportSession, and using AVVideoCompositionCoreAnimationTool to add overlay for final video.
The problem is sometimes the final video is perfect, but sometimes it just give me a black video with sound only even I didn't change anything :(
Anybody who ran into that problem same me please give an idea, thanks!
let mixComposition: AVMutableComposition = AVMutableComposition()
//Add assets here
let mainComposition: AVMutableVideoComposition = AVMutableVideoComposition(propertiesOf: mixComposition)
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = renderSize
mainComposition.renderScale = 1.0
mainComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
mainComposition.instructions = instructions
let exportSession: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
exportSession.videoComposition = mainComposition
exportSession.audioMix = audioMix
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileTypeMPEG4
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously {
// Ended here
}

Tkinter button doesn't respond (has no mouse over effect)

I'm writing a game that has info that is communicated from client to server and from server to client. One specific (non-playing) client is the monitor, which only displays the game board and players. This works fine, the only thing that doesn't work is the quit button on the GUI. A minor thing, but I would like it to work. :) Plus I think that there might be something pretty wrong with the code, even though it works.
I tried all kind of different commands (sys.exit, quit...) and nothing fixed it.
There's no error message, nothing happens with the button at all. No mouse over effect, nothing if I click it. Relevant code (I removed matrix and server logic because I think it's irrelevant - if it isn't I'll post it):
class Main():
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
# Has to be counted up by server class
rounds = 0
# Has to be communicated by server class. If numberwin == numberrobots,
# game is won
numberwin = 0
numberrobots = 2
def draw(self):
if hasattr(self, 'info'):
self.info.destroy()
if hasattr(self, 'quit'):
self.quit.destroy()
print "Main should draw this matrix %s" % self.matrix
[...] lots of matrix stuff [...]
# Pop-Up if game was won
# TODO: Make GUI quittable
if self.numberwin == self.numberrobots:
self.top = Toplevel()
self.msg = Message(self.top, text="This game was won!")
self.msg.pack(side=LEFT)
self.quittop = Button(
self.top, text="Yay", command=self.frame.destroy)
self.quittop.pack(side=BOTTOM)
# TODO: Quit GUI
self.quit = Button(self.frame, text="Quit", command=self.frame.destroy)
self.quit.pack(side=BOTTOM)
# Information on the game
self.info = Label(
self.frame, text="Rounds played: {}, Numbers of robots in win condition: {}".format(self.rounds, self.numberwin))
self.info.pack(side=TOP)
def canvasCreator(self, numberrows, numbercolumns):
# Game board
self.canvas = Canvas(
self.frame, width=numbercolumns * 100 + 10, height=numberrows * 100 + 10)
self.canvas.pack()
class Agent(Protocol, basic.LineReceiver):
master = Tk()
main = Main(master)
# So first matrix is treated differently from later matrixes
flagFirstMatrix = 1
def connectionMade(self):
msg = dumps({"type": "monitor"})
self.sendLine(msg)
print "Sent message:", msg
def dataReceived(self, data):
# Decode the json dump
print "Data received: %s" % data
data = loads(data)
self.main.matrix = np.matrix(data["positions"])
self.main.goals = np.matrix(data["goals"])
self.main.next_move_by_agent = data["next_move"]
self.main.rounds = data["rounds"]
self.main.numberwin = data["win_states"]
if self.flagFirstMatrix == 1:
self.main.numberrows, self.main.numbercolumns = self.main.matrix.shape
self.main.canvasCreator(
self.main.numberrows, self.main.numbercolumns)
self.main.canvas.pack()
self.flagFirstMatrix = 0
self.main.canvas.delete(ALL)
self.main.draw()
self.master.update_idletasks()
self.master.update()
First there is no indentation for class Agent, second for the quit button's "call back" self.frame.destroy is never defined so it doesn't do anything. If you meant tkinter destroy method try self.frame.destroy() or try explicitly defining it. You can also try calling either fram.pack_forget() or fram.grid_forget()
Add master.mainloop() to your last line in terms of the entire lines of code

Why does set_position fail in this code

When I build this same ui in Glade (the program) the resulting code is flawless, when I code it by hand everything works except one thing, the set_position(670) is ignored and the resulting window comes up at about 1" square on my screen.
My goal is to get the left hand pane to instanciate at 670 px wide. I am not concerned about locking the width.
I have tried placing the call to set_position(670):
where it is shown now
2 lines further down
After the self.top.show_all()
Just before the self.top.show_all()
Just after call to pack1
Searching google has lead to no usefull results, and there are no useful answers here that I have found so far.
The pyGtk site indicates that the call can be placed almost anywhere.
The gtk site lists no restrictions.
Most things I have found seem to indicate it is due to the resize/shrink attributes of one of the other widgets, but after numerous attempts at altering the values of everything in the left pane, I am still at a loss. (Note that value changes were tried one or two at a time.)
import gtk
import gobject
class Source(gobject.GObject):
def _emit_signal(self, button, value):
self.emit('choice_changed', self, value)
def __init__(self):
self.__gobject_init__()
# packing treee
# top
# main
# inst_align
# inst_window
# instructions
# opt_align
# opt_buttons
# opt_0 (through opt_5)
# doit_box
# doit
self.top = gtk.Alignment(0.0, 0.0, 1.0, 1.0)
self.main = gtk.HPaned()
self.main.set_position(670)
self.top.add(self.main)
# Build left side components
self.inst_align = gtk.Alignment(0.0, 0.0, 1.0, 1.0)
self.inst_window = gtk.ScrolledWindow(None, None)
self.inst_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.instructions = gtk.TextView(None)
self.instructions.get_buffer().set_text(
"Very long (1200 char) string snipped.")
#pack pane 1
self.inst_window.add(self.instructions)
self.inst_align.add(self.inst_window)
self.main.pack1(self.inst_align, True, False)
# build right side components
self.opt_align = gtk.Alignment(1.0, 0.0, 0.0, 0.0)
self.opt_buttons = gtk.VButtonBox()
self.opt_buttons.set_layout(gtk.BUTTONBOX_START)
self.opt_buttons.set_homogeneous(True)
self.opt_0 = gtk.RadioButton(
None,
"Label 0",
True)
self.opt_1 = gtk.RadioButton(
self.opt_0,
"Label 1",
True)
self.opt_2 = gtk.RadioButton(
self.opt_0,
"Label 2",
True)
self.opt_3 = gtk.RadioButton(
self.opt_0,
"label 3",
True)
self.opt_4 = gtk.RadioButton(
self.opt_0,
"Label 4",
True)
self.opt_5 = gtk.RadioButton(
self.opt_0,
"Label 5",
True)
self.doit_box = gtk.HButtonBox()
self.doit = gtk.Button("Do It !", None, True)
self.doit.expand = False
self.doit.fill = False
self.doit.set_alignment(0.5, 0.0)
# Put the buttons in the box and while were at it, bind their
# released, and pressed options
for i in range(0, 6):
s = "self.opt_" + str(i)
self.opt_buttons.pack_start( eval(s), True, False, 0 )
s1 = s + '.connect("released", self._emit_signal, i)'
s2 = s + '.connect("pressed", self._emit_signal, i)'
exec(s1)
exec(s2)
self.doit_box.pack_start(self.doit, True, False, 0)
self.opt_buttons.pack_start(self.doit_box, True, False, 0)
self.opt_align.add(self.opt_buttons)
self.main.pack2(self.opt_align, True, False)
self.top.show_all()
gobject.type_register(Source)
gobject.signal_new('choice_changed',
Source,
gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE, (Source, gobject.TYPE_INT))
if __name__ == "__main__":
def cb_test(widget, event, value):
print "widget is", widget
print "Value is ", value
return
test = Source()
win = gtk.Window()
win.add(test.top)
win.show_all()
test.connect('choice_changed', cb_test)
gtk.main()
You have to set a window with greater than the position of the HPane divider. Here is a stripped down example:
import gtk
class Source(gtk.Window):
def __init__(self):
super(Source, self).__init__()
label1 = gtk.Label("The first label")
label2 = gtk.Label("The second label")
paned = gtk.HPaned()
paned.add1(label1)
paned.add2(label2)
paned.set_position(600)
self.add(paned)
self.set_size_request(800, 400) # needs sufficient width here
self.connect('delete-event', gtk.main_quit)
self.show_all()
if __name__ == "__main__":
test = Source()
gtk.main()

Tkinter forgetting to finish the function

I am again asking a question on this progressbar project; although this should just be a clarification question.
My code causes for a progressbar to be created to track the creation of a file. The user selects the type of file they want to create and then hits "go" which causes for the file to begin changing and for the progressbar to appear. Progressbar works great. File writing/manipulation works great.
Problem: When the user selects several files to manipulate, despite the progressbars being created correctly, they do NOT update correctly. At first I thought that clicking on a button multiple times causes for tkinter to forget the root.after() function it was doing previously but after playing with a (much simpler) sample code I realized that this is not the case.
Question: How do I make sure tkinter doesn't stop implementing the first function even when the same function is restarted with different parameters?
Below are parts of my code to describe what I am doing.
progbarlock = False # start with the prograssbar marked as not occupied
class guibuild:
def __init__(self):
self.root = root
guibuild.progbarlock = False
global theframe
theframe = Frame(root)
job_name = e.get()
label = Label(theframe,text = job_name).pack(side=LEFT,padx =2)
self.progbar = Meter(theframe) #makes the progressbar object
self.progbar.set(0.0) #sets the initial value to 0
self.progbar.pack(side=LEFT)
self.counter = 0
self.i = float(0) #i is the value set to the progressbar
def stop_progbar(self):
self.progbar.stop()
def begin(self):
self.interval()
self.Status_bar()
theframe.pack(anchor="s")
def interval(self):
if guibuild.progbarlock == False:
guibuild.progbarlock = True
def update(self):
the_file = open('running_file.json')
data = json.load(the_file)
curr = data["current_line"]
total = data["total_lines"]
if self.i == 1.0:
self.stop_progbar
rint "100% - process is done"
self.root.after_cancel(self.interval)
elif curr == self.counter:
self.root.after(5000, self.interval)
elif curr == self.counter+1:
self.i += 1.0/total
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter += 1
self.stop_progbar
self.root.after(5000, self.interval)
elif curr > self.counter+1:
self.i += 1.0/total*(curr-self.counter)
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter = curr
self.stop_progbar
self.root.after(5000, self.interval)
else:
print "something is wrong - running.json is not available"
self.root.after(5000, self.interval)
guibuild.progbarlock = False
def start_process():
makeRequest() #this is defined much earlier in the code and includes all the file creation and manipulation
guibuild().begin()
button4 = Button(root,text="GO", command = start_process).pack()
NOTE:makeRequest() depends entirely on user input and the user input changes each time "go" is pressed.