I wrote a code in CodeSkultor, which made use of Simplegui module but that's not available in Python 2.7, obviously. I know we can make use of SimpleGUICS2Pygame module and I have set it up along with pygame but the below code for a simple Guess the Number game still doesn't seem to display the graphics. Couldn't attach a screenshot. Any ideas, anyone? Link to CodeSkultor program is here - http://www.codeskulptor.org/#user40_G13NSFMPzs_4.py
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
#import simpleplot
# define global variables
n = 0
min = 0
sec = 0
tenth_sec = 0
is_running = False
count_stop = 0
count_success_stop = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
global sec
global tenth_sec
global min
#global is_running
sec = int (t / 10)
tenth_sec = t % 10
min = int (t / 600)
#return sec
if sec < 10:
return str(min) + ":0" + str(sec) + ":" + str(tenth_sec)
elif sec >= 10 and sec <= 59:
return str(min) + "0:" + str(sec) + ":" + str(tenth_sec)
elif sec >= 60:
sec = sec % 60
if sec >=10:
return str(min) + ":" + str(sec) + ":" + str(tenth_sec)
else:
return str(min) + ":" + "0" + str(sec) + ":" + str(tenth_sec)
#is_running = True
# define event handlers for buttons; "Start", "Stop", "Reset"
def button_start():
global count_start
global is_running
global check
timer.start()
is_running = True
check = True
def button_stop():
global count_stop
global count_success_stop
if timer.is_running():
count_stop += 1
if tenth_sec == 0:
count_success_stop += 1
timer.stop()
def button_reset():
global n
global count_stop
global count_success_stop
n = 0
count_stop = 0
count_success_stop = 0
timer.stop()
# define event handler for timer with 0.1 sec interval
def timer_handler():
global n
n = n + 1
#print n
# define draw handler
def draw_handler(canvas):
canvas.draw_text(format(n),[120,150],30,"Black")
canvas.draw_text(str(count_stop),[230,40],20,"Green")
canvas.draw_text("/",[250,40],20,"Green")
canvas.draw_text(str(count_success_stop),[265,40],20,"Green")
# create frame
# register event handlers
frame = simplegui.create_frame("Stopwatch", 300, 300)
frame.add_button("Start",button_start)
frame.add_button("Stop",button_stop)
frame.add_button("Reset",button_reset)
timer = simplegui.create_timer(100, timer_handler)
# start frame
frame.start()
frame.set_draw_handler(draw_handler)
You must start the frame at the end.
See https://simpleguics2pygame.readthedocs.io/en/latest/Compatibility.html
"With SimpleGUICS2Pygame, Frame.start() is blocking until Frame.stop() execution or closing window. So timers must be started before, and states must be initialized before. (Or maybe after by a handler function.)"
Related
I am trying to get the percentage. Based on the code below, what else should I do?
- ********#Libraries
import RPi.GPIO as GPIO #Import GPIO library
import time #Import time library
GPIO.setmode(GPIO.BCM) #GPIO Mode (BOARD / BCM)
GPIO_TRIGGER = 18
GPIO_ECHO = 24 #set GPIO Pins
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
GPIO.output(GPIO_TRIGGER, True) # set Trigger to HIGH
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False) # set Trigger after 0.01ms to LOW
StartTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO) == 0: # save StartTime
StartTime = time.time()
while GPIO.input(GPIO_ECHO) == 1: # save time of arrival
StopTime = time.time()
TimeElapsed = StopTime - StartTime # time difference between start and arrival
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
def percentage(temp) :
percentage = round(((binheight - temp)/binheight)*100, 2)
return percentage
if __name__ == '__main__':
try:
while True:
dist = distance()
percent = percentage(dist)
print ("Measured Distance = %.1f cm" % dist)
print ("Percentage", percent, "%")
time.sleep(1)
except KeyboardInterrupt: # Reset by pressing CTRL + C
print("Measurement stopped by User")
GPIO.cleanup()********
I am trying to display a value by increasing it incrementally until the desired value is reached.
I have tried two ways of doing it and neither works.
def temperature_gauge(self):
self.dT = self.dU.get() / (float(self.entry_m.get()) * float(self.entry_Cv.get()))
self.counter = 0
while self.counter >= 0:
self.c.delete(self.L2)
self.L2 = self.c.create_text(90,345, text=self.counter)
self.c.update()
self.counter += 1.00
if self.counter == float(self.dT):
break
def temperature_gauge(self):
self.dT = self.dU.get() / (float(self.entry_m.get()) * float(self.entry_Cv.get()))
self.counter = 0
for i in range(0, int(self.dT)):
self.number_text = self.c.create_text(90,345, text=(i))
self.c.update()
time.sleep(0.1)
self.c.delete(self.number_text)
I'm very new to python and I've been working on a basic calculator within python for the last few hours (rhetorical I know, given what python has built in, but it's part of my learning process), I've run into an error I can't seem to fix, generally I'm able to get my scripts on their feet and running with the assistance of a couple of Google searches but this one has me stumped. I'm getting a syntax error where I have an else, and while at first I was pretty sure it was a structure issue, rewriting the script didn't fix anything, vague I know, so here's the script (I've marked the spot with a comment) :
def Calculator():
tempnums = [] #stores nums only
tempfuncs = [] #stores funcs only
tmpfuncs = {} #stores funcs only
times = lambda multiply: tempnums[0]*tempnums[1]
div = lambda divide: tempnums[0]%tempnums[1]
plus = lambda add: tempnums[0]+tempnums[1]
minus = lambda subtract:tempnums[0]-tempnums[1]
done = 0
varnum = 0
xtimes = 0
divtimes = 0
plustimes = 0
mintimes = 0
while done == 0: #USER INPUT PROCESS
varnum = varnum + 1
tempint = input() #nums
exec("num%d = tempint" % (varnum))
function = raw_input() #functions
if function != "=":
if function == 'x':
if x not in tmpfuncs:
xtimes = xtimes + 1
tmpfuncs[x] = times
else:
xtimes = xtimes + 1
exec("tmpfuncs[x%d] = times" % (xtimes)
else: #ERROR COMES HERE
if function == '//':
if dv not in tmpfuncs:
divtimes = divtimes + 1
tmpfuncs[dv] = div
else:
divtimes = divtimes + 1
exec("tmpfuncs[dv%d] = div" % (divtimes)
if function == '+':
if pls not in tmpfuncs:
plustimes = plustimes + 1
tmpfuncs[pls] = plus
else:
plustimes = plustimes + 1
exec("tmpfuncs[pls%d] = plus" % (plustimes)
if function == '-':
if mn not in tmpfuncs:
mintimes = mintimes + 1
tmpfuncs[mn] = minus
else:
mintimes = mintimes + 1
exec("tmpfuncs[mn%d] = minus" % (mintimes)
else: #user has selected to calculate input
done = 1
for i in range(1, varnum + 1):
exec("tempnums.append(num%d)" % (i)) #adding nums to a list with dynamic var names
print tmpfuncs
#next we'll make it so that tempnums[0] is the changing result as we use tempnums 0 and 1 to calculate the answer, deleting one as we go until there is only zero
Calculator()
Calculator()
I'm hoping this is legible as I'm posting from mobile (as a matter of fact I'm writing this from mobile as well).
The line above the else is missing a closing parens:
exec("tmpfuncs[x%d] = times" % (xtimes)
should be
exec("tmpfuncs[x%d] = times" % (xtimes))
The same error occurs in many other of your exec lines. Also, I suggest you consider restructuring your code so you do not need to use exec at all.
I'm trying to figure out how to use timer loop in cv.putText.
This is what I have so far:
def draw_result(self, frame, result):
x,y,w,h = self.metrics
c = self.get_colour()
cv.PutText(frame, "%0.0f"%result, (x+15,y-15), self.large_font_outline, c[1])
cv.PutText(frame, "%0.0f"%result, (x+15,y-15), self.large_font, c[0])
You can use time.time().
import time
inittime = time.time()
secs = 30
while 1:
if time.time() >= inittime+secs:
inittime = time.time()
draw_result(self, frame, result)
this code will call draw_result in the last line every 30 seconds.
I have some problems the first one is that I can't update the plot limits of the y axis and the second is that I want to see 6 lines from each sensor, as you can see in the picture I see only one if I make some changes I see all the sensors variations in one line
here is the code where I create the plot and a picture of this:
http://i.imgur.com/ogFoMDJ.png?1
# Flag variables
self.isLogging = False
# Create data buffers
self.N = 70
self.n = range(self.N)
self.M = 6 # just one lead - i.e. 1 number per sample
self.x = 0 * numpy.ones(self.N, numpy.int)
# Data logging file
self.f = 0
# Create plot area and axes
self.x_max = 500
self.x_min = 330
self.fig = Figure(facecolor='#e4e4e4')
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
self.canvas.SetPosition((330,50))
self.canvas.SetSize((550,280))
self.ax = self.fig.add_axes([0.08,0.1,0.86,0.8])
self.ax.autoscale(False)
self.ax.set_xlim(0, self.N - 1)
self.ax.set_ylim(self.x_min, self.x_max)
self.ax.plot(self.n,self.x)
# Filter taps
self.taps = [0, 0, 0]
# Create timer to read incoming data and scroll plot
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.GetSample, self.timer)
And here is where I grab the data and I try to update the limits of the plot
if len(sample_string) != 6:
sample_string = sample_string[0:-1]
self.taps[1:3] = self.taps[0:2]
self.taps[0] = int(array[1])
#value = 0.5 * self.taps[0] + 0.5 * self.taps[2]
value = self.taps[0]
self.x[0:self.N-1] = self.x[1:]
self.x[self.N-1] = value
# print sample to data logging file
if self.f != 0:
self.f.write(str(value))
self.f.write("\n")
# update plot limits
maxval = max(self.x[:])
minval = min(self.x[:])
self.x_max += ((maxval + 10) - self.x_max) / 100.0
self.x_min -= (self.x_min - (minval - 10)) / 100.0
# Update plot
self.ax.cla()
self.ax.autoscale(False)
self.ax.set_xlim(0, self.N - 1)
self.ax.set_ylim(self.x_min, self.x_max)
self.ax.plot(self.n, self.x)
self.canvas.draw()
if b7 == True:
self.textctrl0.Clear()
self.textctrl0.AppendText(array[1])
self.textctrl1.Clear()
self.textctrl1.AppendText(array[2])
self.textctrl2.Clear()
self.textctrl2.AppendText(array[3])
self.textctrl3.Clear()
self.textctrl3.AppendText(array[4])
self.textctrl4.Clear()
self.textctrl4.AppendText(array[5])
self.textctrl5.Clear()
self.textctrl5.AppendText(array[6])
b7=False
p.s I removed the faulty code where I tried to add the other sensors,here is only the working code for the one sensor plot..