Mouse selection of images with Psychopy - python-2.7

I have created two stimuli(red and green rectangles) as stimuli in Psychopy. Also, I have enabled mouse movements to four directions. Using the function[mouse.getPressed()] in Psychopy for selecting the stimuli, I am facing some issues.
Basically, I want the mouse to move in four directions, and when the mouse reaches red/green rectangle stimuli, I need to select that stimuli and change its color to blue.
Can anyone look into the issue and help me to resolve the same?
Here is my code:
from psychopy import visual, core, event
import numpy as np
# Create a window.
# For configuring and debugging the code turn off full screen.
fullscr = False
win = visual.Window(
[1200,1000],
monitor="testMonitor",
units="deg",
fullscr=fullscr
)
#cursor = visual.Circle(win, radius=0.2)
#cursor = visual.CustomMouse(win,
# leftLimit=-10, topLimit=10, rightLimit=10, bottomLimit=-10,
# showLimitBox=True, clickOnUp=True)
pos_zero = (0, 0)
cursor = visual.Rect(
win=win,
size=400,
pos=pos_zero,
opacity=0
)
mouse = event.Mouse(visible=True)
# Sinusoidal control version.
freq_one = 0.5
freq_two = 1.5
# Colors of the rectangles.
#color_zero='black'
color_one = 'red'
color_two = 'green'
# Positions of the rectanges.
pos_one = (-10, 0)
pos_two = (10, 0)
start = core.getTime()
cnt = 0
cursor.pos = mouse.getPos()
print cursor.pos
while cnt<600:
second = core.getTime() - start
sin_val_one = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_one))
sin_val_two = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_two))
#while not mouse.getPressed()[0]:
# Do something if mouse moved
for key in event.getKeys():
if key == 'escape':
core.quit()
elif key == "right":
cursor.pos = cursor.pos + (2,0)
elif key =="left":
cursor.pos = cursor.pos - (2,0)
elif key =="up":
cursor.pos = cursor.pos + (0,2)
elif key =="down":
cursor.pos = cursor.pos - (0,2)
#if cursor.pos == pos_one:
# mouse.getpressed(rect_one)
#elif cursor.pos == pos_two:
# mouse.getpressed(rect_two)
mouse.setPos(cursor.pos)
mouse.lastPos = cursor.pos
rect_one = visual.Rect(
win=win,
fillColor=color_one,
lineColor=color_one,
size=15,
pos=pos_one,
opacity=sin_val_one
)
rect_two = visual.Rect(
win=win,
fillColor=color_two,
lineColor=color_two,
size=15,
pos=pos_two,
opacity=sin_val_two
)
#images = [rect_one, rect_two]
#for image in images:
# if mouse.isPressedIn(image):
# pressed_shape = shape
#
# pressed_image.fillColor = 'blue'
# pressed_image.draw()
# print pressed_image.name
rect_one.draw()
rect_two.draw()
cursor.draw()
win.flip()
cnt += 1
win.close()
Any help is greatly appreciated. Thanks!

I made several changes and post the updated code below. It's significantly shorter and simpler.
Removed everything using mouse. Since you just want something visual to move on key presses, there's no need to invoke the mouse - especially when you actually don't want subjects to use the mouse...
Create the colored shapes once, then updating the color during runtime. This is significantly faster, i.e. avoids dropping frames.
Changed the cursor size. It was 400 degrees!
Removed the line around the rectangles so that only fillColor needs to be changed on overlap.
A few other simplifications.
Here is the code:
from psychopy import visual, core, event
import numpy as np
# Settings
fullscr = False
directions = {'left': (-2,0), 'right': (2,0), 'up': (0, 2), 'down': (0, -2)}
freq_one = 0.5 # # Sinusoidal control
freq_two = 1.5
# Create a window.
win = visual.Window([1200,1000], monitor="testMonitor", units="deg", fullscr=fullscr)
# The two rectangles
rect_one = visual.Rect(win=win, fillColor='red', lineColor=None, size=15, pos=(-10, 0))
rect_two = visual.Rect(win=win, fillColor='green', lineColor=None, size=15, pos=(10, 0))
# Cursor
cursor = visual.Circle(win, fillColor='white', radius=0.2)
# Run five trials
for trial in range(5):
# Set to initial condition
rect_one.fillColor = 'red'
rect_two.fillColor = 'green'
cursor.pos = (0, 0)
# Start task
start = core.getTime()
for frame in range(600):
# Set rectangle opacities
second = core.getTime() - start
rect_one.opacity = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_one))
rect_two.opacity = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_two))
# Show it
rect_one.draw()
rect_two.draw()
cursor.draw()
win.flip()
# Get keyboard responses and change color if there is overlap
for key in event.getKeys():
if key == 'escape':
core.quit()
elif key in directions.keys(): # if this is a key corresponding to a direction
cursor.pos += directions[key] # Lookup the pos change in "directions" and add it to current position
if cursor.overlaps(rect_one):
rect_one.fillColor = 'blue'
if cursor.overlaps(rect_two):
rect_two.fillColor = 'blue'

Related

Speed up effect of gravity on python

I figured out how to include gravity in the platform game I am working on.
The problem is, the sprite jumps up and falls down too slowly. Moving horizontally is not a problem but the sprite significantly slows down when jumping.
How would I solve this problem? Thank you.
Here is the part of my code for gravity. :
def update(self):
""" Move the player. """
# Gravity
self.calc_grav()
# Move left/right
self.rect.x += self.change_x
# See if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# If we are moving right,
# set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
elif self.change_x < 0:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
elif self.change_y < 0:
self.rect.top = block.rect.bottom
# Stop our vertical movement
self.change_y = 0
def calc_grav(self):
""" Calculate effect of gravity. """
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += 0.5
# See if we are on the ground.
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height
def jump(self):
""" Called when user hits 'jump' button. """
# move down a bit and see if there is a platform below us.
# Move down 2 pixels because it doesn't work well if we only move down
# 1 when working with a platform moving down.
self.rect.y += 2
platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
self.rect.y -= 2
# If it is ok to jump, set our speed upwards
if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
self.change_y = -12
# Player-controlled movement:
def go_left(self):
""" Called when the user hits the left arrow. """
self.change_x = -8
def go_right(self):
""" Called when the user hits the right arrow. """
self.change_x = 8
def stop(self):
""" Called when the user lets off the keyboard. """
self.change_x = 0

AttributeError: draw_artist can only be used after an initial draw which caches the render

My requirement is to plot the data in polar graph. However I need to keep polar graph in particular angle to looks like "V" shape and data need to plotted in between the particular angle.
In python I don't find a solution to keep the polar graph in particular angle, Example : Graph should be display in between -60 to 60 degree radius. To achieve that I have looked into couple of existing examples and creating required polar graph with FloatingSubplot functions. However I am hitting the issue , when we try to use along with function animation function with blit=True. Error message is displayed is "AttributeError: draw_artist can only be used after an initial draw which caches the render"
Here is my code.
#
import matplotlib
matplotlib.use('Qt4Agg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.animation as animation
import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib.transforms import Affine2D
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist import angle_helper
from mpl_toolkits.axisartist.grid_finder import MaxNLocator, DictFormatter
from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot
plt.close('all')
fig = plt.figure('Practice', dpi=100) # To set the fig title as pratice
ax1 = fig.add_subplot(2, 2, 1) # subplot for 1st plot
plt.ion()
ax1.grid(True)
def fractional_polar_axes(f, thlim=(0, 120), rlim=(0, 20), step=(30, 0.25),
thlabel='theta', rlabel='r', ticklabels=True, theta_offset=0, rlabels=None):
'''Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta
and r are really just hints for the locators.'''
th0, th1 = thlim # deg
r0, r1 = rlim
thstep, rstep = step
tr_rotate = Affine2D().translate(theta_offset, 0)
# scale degrees to radians:
tr_scale = Affine2D().scale(np.pi / 180., 1.)
# pa = axes(polar="true") # Create a polar axis
pa = PolarAxes
tr = tr_rotate + tr_scale + pa.PolarTransform()
theta_grid_locator = angle_helper.LocatorDMS((th1 - th0) // thstep)
r_grid_locator = MaxNLocator((r1 - r0) // rstep)
theta_tick_formatter = angle_helper.FormatterDMS()
if rlabels:
rlabels = DictFormatter(rlabels)
grid_helper = GridHelperCurveLinear(tr,
extremes=(th0, th1, r0, r1),
grid_locator1=theta_grid_locator,
grid_locator2=r_grid_locator,
tick_formatter1=theta_tick_formatter,
tick_formatter2=rlabels)
a = FloatingSubplot(f, 222, grid_helper=grid_helper)
# a = Subplot(f,753, grid_helper=grid_helper)
# f.add_subplot(7,5,(3,34))
f.add_subplot(a)
# adjust x axis (theta):
print(a)
a.axis["bottom"].set_visible(False)
a.axis["top"].set_axis_direction("bottom") # tick direction
a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
a.axis["top"].major_ticklabels.set_axis_direction("top")
a.axis["top"].label.set_axis_direction("top")
a.axis["top"].major_ticklabels.set_pad(10)
# adjust y axis (r):
a.axis["left"].set_axis_direction("bottom") # tick direction
a.axis["right"].set_axis_direction("top") # tick direction
a.axis["left"].toggle(ticklabels=True, label=bool(rlabel))
# add labels:
a.axis["top"].label.set_text(thlabel)
a.axis["left"].label.set_text(rlabel)
# create a parasite axes whose transData is theta, r:
auxa = a.get_aux_axes(tr)
print(auxa)
# make aux_ax to have a clip path as in a?:
auxa.patch = a.patch
# this has a side effect that the patch is drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to prevent this:
a.patch.zorder = -2
# add sector lines for both dimensions:
thticks = grid_helper.grid_info['lon_info'][0]
rticks = grid_helper.grid_info['lat_info'][0]
print(grid_helper.grid_info['lat_info'])
for th in thticks[1:-1]: # all but the first and last
auxa.plot([th, th], [r0, r1], ':', c='grey', zorder=-1, lw=0.5)
for ri, r in enumerate(rticks):
# plot first r line as axes border in solid black only if it isn't at r=0
if ri == 0 and r != 0:
ls, lw, color = 'solid', 1, 'black'
else:
ls, lw, color = 'dashed', 0.5, 'grey'
# From http://stackoverflow.com/a/19828753/2020363
auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False,
transform=auxa.transData._b, zorder=-1))
return auxa
def animate(i):
global loopcount, th, r
th = th+.1
r = r+.1
datapoints.set_offsets(np.vstack((th,r)).T)
#print("in animate")
return datapoints,
if __name__ == '__main__':
r_locs = [0,5,10, 15, 20]
r_labels = ['0', '5', '10', '15', '20']
r_ticks = {loc: label for loc, label in zip(r_locs, r_labels)}
a1 = fractional_polar_axes(fig, thlim=(-60, 60), step=(20, 5),
theta_offset=90, rlabels=r_ticks)
th= 20
r=10
a1.scatter(th,r , c = 'r', alpha = 0.5, linewidths = '.2', s = 20) # plotting the line at thetha 20 and radius 10
datapoints = a1.scatter([], [], c='b', alpha = 0.5, linewidths = '.2', s = 20) # creating scatter line with given instruction,
ani = animation.FuncAnimation(fig, animate, frames=30, interval=20, blit=True)
plt.show(block=True)
#
"""
Above code is working perfectly fine with blit=False and also same solution working fine with line and scatter plotting in normal graph.
Please someone help me to resolve the issue.
"""

User controlled sprite stuck in box. Python 2.7.9 w/Pygame

Thanks for looking at my question and helping me out. I have a user controlled sprite that should cause the screen to shift around the sprite's position, kinda like an old Gameboy Pokemon game, yet that does not happen. Instead my sprite is stuck inside a box of coordinates that I used to help define parameters for background shift. This is the code I believe is causing this:
# Shift world left (-x)
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
# Shift world right (+x)
if player.rect.left <= 130:
diff = 130 - player.rect.left
player.rect.left = 130
current_level.shift_world_x(diff)
# Shift world up (-y)
if player.rect.top <= 100:
diff = 100 - player.rect.top
player.rect.top = 100
current_level.shift_world_y(diff)
# Shift world down (y)
if player.rect.bottom >= 380:
diff = player.rect.bottom - 380
player.rect.bottom = 380
current_level.shift_world_y(-diff)
If I put a # next to player.rect.right = 510, or any of the other three varients, my sprite can move freely, yet the screen will not shift.
Zip file with all assets is here:
https://www.dropbox.com/s/3g2w0mv1fuupetl/DoneGeon.zip?dl=0
The entirety of my code is as follows:
import pygame
"""---Global Constants---"""
# Colors
BLACK = (0, 0, 0)
# Screen Variables
screen_x = 720
screen_y = 480
# Background variables
back_x = 0
back_y = -243
back_x_change = 0
back_y_change = 0
class Player(pygame.sprite.Sprite):
"""---User Controled Character---"""
# Methods
def __init__(self):
"""---Contructor Function---"""
# Call parent's constructor
pygame.sprite.Sprite.__init__(self)
# Load player image
self.image = pygame.image.load("player.png").convert()
# Set referance to image "hit box"
self.rect = self.image.get_rect()
# Set speed of player
self.change_x = 0
self.change_y = 0
def update(self):
"""---Move the Player---"""
# Move left/right
self.rect.x += self.change_x
# Move up/down
self.rect.y += self.change_y
# User controlled movements
def go_left(self):
self.change_x = -3
def go_right(self):
self.change_x = 3
def go_up(self):
self.change_y = -3
def go_down(self):
self.change_y = 3
def stop_x(self):
self.change_x = 0
def stop_y(self):
self.change_y = 0
class Barrier(pygame.sprite.Sprite):
"""---Barriers that prevent player from passing---"""
def __init__(self,width,height):
""" Barrier constructor """
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width,height])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
class Level():
"""---All levels will spawn from this generic class---"""
def __init__(self,player):
""" Needed for when sprites collide with player """
self.barrier_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.player = player
# Distance world has been shifted left/right
self.world_shift_x = 0
# Background image
background_base = None
background_layera = None
# Distance world has been shifted up/down
self.world_shift_y = 0
def update(self):
""" Update everything on level """
self.barrier_list.update()
self.enemy_list.update()
def draw(self,screen):
""" Draw everything on level """
# Draw barriers
self.barrier_list.draw(screen)
# Draw the base layer
screen.blit(self.background_base,(back_x,back_y))
# Draw all sprites
self.enemy_list.draw(screen)
# Draw Layer A
screen.blit(self.background_layera,(back_x,back_y))
def shift_world_x(self,shift_x):
""" When character moves left/right, everything must follow """
# Track shift amount
self.world_shift_x += shift_x
# Go through all list and shift
for barrier in self.barrier_list:
barrier.rect.x += shift_x
for enemy in self.enemy_list:
enemy.rect.x += shift_x
def shift_world_y(self,shift_y):
""" When character moves up/down, everything must follow """
# Track shift amount
self.world_shift_y += shift_y
# Go through all list and shift
for barrier in self.barrier_list:
barrier.rect.y += shift_y
for enemy in self.enemy_list:
enemy.rect.y += shift_y
class Level_1(Level):
"""---Forest 1---"""
def __init__(self,player):
""" Create the level """
# Call parent constructor
Level.__init__(self,player)
self.level_limit_x = -1912
self.level_limit_y = 1080
# Make background
self.background_base = pygame.image.load("base1.png").convert()
self.background_layera = pygame.image.load("layera1.png").convert()
self.background_layera.set_colorkey(BLACK)
# List with w, h, x = 32, y = 32 of barriers
# Remove comment to activate-> level = []
# Go through the list above and add barriers
# Remove comment to activate-> for barriers in level:
def main():
"""---Main Program---"""
pygame.init()
# Set screen size and caption
size = (screen_x,screen_y)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("DoneGeon")
# Create Player
player = Player()
# Create all levels
level_list= []
level_list.append(Level_1(player))
# Set current level
current_level_no = 0
current_level = level_list[current_level_no]
# Add all sprites
active_sprite_list = pygame.sprite.Group()
# Add player
player.level = current_level
player.rect.x = 360
player.rect.y = 240
active_sprite_list.add(player)
# Loop until closed
done = False
# Screen update rate
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
"""---Main event loop---"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
"""---User Controls---"""
# Key Pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.go_up()
if event.key == pygame.K_DOWN:
player.go_down()
# Key Released
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player.stop_x()
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player.stop_y()
"""---Game Logic---"""
# Update Player
active_sprite_list.update()
# Update items in level
current_level.update()
# Shift world left (-x)
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
# Shift world right (+x)
if player.rect.left <= 130:
diff = 130 - player.rect.left
player.rect.left = 130
current_level.shift_world_x(diff)
# Shift world up (-y)
if player.rect.top <= 100:
diff = 100 - player.rect.top
player.rect.top = 100
current_level.shift_world_y(diff)
# Shift world down (y)
if player.rect.bottom >= 380:
diff = player.rect.bottom - 380
player.rect.bottom = 380
current_level.shift_world_y(-diff)
"""---Draw below here---"""
current_level.draw(screen)
active_sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main()
Thank you for any advice!
I think you'll find this easier to track down if you log the changes in player x and world x. Often with games small changes aren't visible so logging is the only way to monitor what's happening in the game loop.
I haven't tested this but my bet is that you've got a negative in the wrong place. This:
def shift_world_x(self,shift_x):
""" When character moves left/right, everything must follow """
suggests that if the player right edge moves past the world right edge the world right edge should extend to match the player but this code does the reverse:
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
If the player.right moves to 513 diff will be 3 so shift_world_x will be called with -3, moving the world box left to 507. Player right will then be set to 510 so the player right will still be outside the box the next loop. This suggests that the world image will drift to the left with the player sprite stuck at the right edge but it sounds like it's trapped against the right edge (I'm focussing on one edge because the logic is the same for all).
If you log player.rect.right and world.rect.right in the if shown above you should see the values as they change and get a better feel for what the game logic is doing.

Drawing a Continuos line in Pygame

Is there a module in pygame to draw a continuos line? I am aware of pygame.draw.line() and pygame.draw.circle(), the last one i am using now, but it will result in distinct circles if i draw fast over the screen and not in a line. Any one can help?
Remember previous position and use pygame.draw.line() to draw line from old position to new position.
-
My old example - use keys left/right to change direction of moving point
import pygame
import math
# === constants === (UPPER_CASE names)
RED = (255, 0 , 0)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# === main ===
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# --- objects ---
# convert tuple to list
pos_new = list(screen_rect.center)
pos_old = list(screen_rect.center)
speed = 5.0
angle = 0.0
# --- mainloop ---
clock = pygame.time.Clock()
running = True
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
angle -= 10
if keys[pygame.K_RIGHT]:
angle += 10
# --- updates ---
if angle >= 360:
angle -= 360
elif angle < 0:
angle += 360
pos_new[0] += int(speed * math.cos(math.radians(angle)))
pos_new[1] += int(speed * math.sin(math.radians(angle)))
# --- draws ---
if pos_new != pos_old:
pygame.draw.line(screen, RED, pos_new, pos_old)
pos_old = pos_new[:]
pygame.display.flip()
# --- FPS ---
clock.tick(25)
# --- the end ---
pygame.quit()
(source: http://blog.furas.pl/przyklad-rysowania-linii-za-poruszajacym-sie-graczem-w-pygame.html)

Python update the plot limits and multiple lines in the plot

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..