"pygame.error: display Surface quit" while loading - python

So I'm making a game to test my programming skills and I'm trying to use pygame but when i try and load a level map it says the surface has quit. I have no idea why.
This is the load code:
def load(self):
print(os.listdir())
file = input('>>> file name = ')
try:
self.Dir = os.getcwd()
path = os.path.join(self.Dir, "maps", file)
data = pickle.load(open(path, 'rb'))
except OSError as error:
print('Not file ', path)
print(error)
else:
self.grid = data[0]
self.blocks = data[1]
Thanks in advance
EDIT:
this is the trace back
Traceback (most recent call last):
File "F:\PROGRAMS\snow\mapmaker_v2.py", line 169, in <module>
a.loop()
File "F:\PROGRAMS\snow\senpy.py", line 95, in loop
self.blocks.draw(self.screen)
File "F:\BMDSIT\Portable Python 3.2.5.1\App\lib\site-packages\pygame\sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
pygame.error: display Surface quit
EDIT 2:
This is the loop code where it happens:
(The load command is in the self.keyboard() function.)
def loop(self):
print('looping')
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('quiting :(')
pygame.display.quit()
quit('User quit')
self.screen.fill((237, 237, 237))
self.keys = pygame.key.get_pressed()
self.mos = pygame.mouse.get_pressed()
self.mouse()
self.keyboard()
#screen.blit(player,player.pos)
self.blocks.draw(self.screen)
self.extraLoop()
pygame.display.flip()
print('done looping')

You can't pickle a Surface object.
If you want to pickle an object that contains a Surface, remove it before saving it to disk; and store the name of the image file or a string representation of the Surface instead in the object.

Related

I have this error : raise turtle.Terminator

I hope it run and do not stop.
I'm making Conway's Game of Life,
if my code look stupid, please help me, I'm only 11.
I use the details from wiki, if it's wrong , please tell me.
Thankyou!
import turtle,random
START_POSITION=[]
def ReStart():
global START_POSITION
#START_POSITION.clear()
y=500
x=-500
for i in range(1,26):
for a in range(1,26):
START_POSITION.append(eval(f"({x},{y})"))
x+=20
x=(0-300)
y-=20
return True
ReStart()
screen=turtle.Screen()
class Cell:
def __init__(self):
self.cells=[]
self.make_body()
self.a()
self.Alive(screen)
def make_body(self):
global START_POSITION
for i in START_POSITION:
seg=turtle.Turtle(shape="square")
seg.color("White")
seg.penup()
seg.goto(i[0],i[1])
self.cells.append(seg)
The error saids:
Traceback (most recent call last):
File "C:/Users/****/Desktop/寫程式/the life game.py", line 145, in <module>
cell=Cell()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 20, in __init__
self.make_body()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 29, in make_body
seg.goto(i[0],i[1])
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1777, in goto
self._goto(Vec2D(x, y))
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 3180, in _goto
self._update()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2661, in _update
self._update_data()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2647, in _update_data
self.screen._incrementudc()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1293, in _incrementudc
raise Terminator
turtle.Terminator
I'm totally stuck on this,please help me.
I've reworked your code fragment into what I believe you are trying to do. Avoid eval as it can cause endless problems. Your use of global in this context isn't valid. See if this works for you:
from turtle import Screen, Turtle
class Body:
def __init__(self, positions):
self.cells = []
self.make_body(positions)
# self.a()
# self.Alive(screen)
def make_body(self, positions):
for position in positions:
cell = Turtle(shape='square')
cell.fillcolor('white')
cell.penup()
cell.goto(position)
self.cells.append(cell)
def restart():
start_positions.clear()
y = 250
for _ in range(25):
x = -250
for _ in range(25):
start_positions.append((x, y))
x += 20
y -= 20
start_positions = []
screen = Screen()
screen.setup(550, 550)
screen.bgcolor('black')
screen.tracer(False)
restart()
my_body = Body(start_positions)
screen.tracer(True)
screen.exitonclick()
Since I've turned off tracer() for speed, call screen.update() whenever you're ready for the user to see the most recent changes.

Nanpy Servo Control

*Nanpy allows for a Raspi to have an Arduino slave through python
Right now I'm having extreme difficulty in using the nanpy Servo package, and I cant get it to run correctly. I'm using it to make a robot that is wirelessly controlled from a computer, this is what I have for code:
from nanpy import (ArduinoApi, SerialManager)
import pygame
from nanpy import Servo
import time
pygame.init()
a=0
d=0
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Console")
try :
connection = SerialManager()
ard = ArduinoApi(connection = connection)
run = True
except:
print("Connection Failed!")
servoA = Servo(2)
servoD = Servo(4)
while run :
for event in pygame.event.get():
keys = pygame.key.get_pressed()
# if (event.type==pygame.KEYDOWN):
if keys[pygame.K_s] and keys[pygame.K_a]:
a=a-1
servoA.write(a)
elif keys[pygame.K_s] and keys[pygame.K_d]:
d=d-1
servoD.write(d)
elif keys[pygame.K_w]:
a=a+1
d=d+1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_s]:
a=a-1
d=d-1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_d]:
d=d+1
servoD.write(d)
elif keys[pygame.K_a]:
a=a+1
servoA.write(a)
elif keys[pygame.K_t]:
run=False
pygame.quit()
This is the error the python shell throws:
Traceback (most recent call last):
File "/home/pi/Desktop/nanpy/RobotCode.py", line 28, in <module>
servoA = Servo(2)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/servo.py", line 9, in __init__
self.id = self.call('new', pin)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 150, in call
return _call(self.namespace, self.id, args, self.connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 47, in _call
ret = return_value(connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 18, in return_value
return serial_manager.readline().replace('\r\n', '')
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/serialmanager.py", line 101, in readline
raise SerialManagerError('Serial timeout!')
nanpy.serialmanager.SerialManagerError: Serial timeout!
How can I fix this, and/or what am I doing wrong?
You need to specify the port of the Arduino. So could you try:
connection = SerialManager(device='/dev/ttyACM0')
or whatever port you are using.
update the configuration file to use the servo and upload it to arduino using the IDE then run this program.
you can find the cfg.h file in nanpy-firmware/nanpy folder.

Displaying Cards in Python with tkinter [duplicate]

I am working on a python program that displays a series of images using Tkinter and ImageTk. I have not been able to display more than a single image. Below is a small complete program that reproduces the error. The program searches the current directly recursively for jpg files, and displays them as the uses presses Enter.
import Tkinter, ImageTk,os, re
def ls_rec(direc):
try:
ls = os.listdir(direc)
except Exception as e:
return
for f in os.listdir(direc):
fpath = os.path.join(direc, f)
if os.path.isfile(fpath):
yield fpath
elif os.path.isdir(fpath):
for f2 in iterate_dir(os.path.join(direc,f)):
yield f2
images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0
def get_next_image(event = None):
global i, img
i+=1
img = ImageTk.PhotoImage(images[i])
label.config(image=img)
label.image = img
top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
The program fails with the following traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/myuser/Projects/sample_images.py", line 1, in <module>
import Tkinter, ImageTk,os, re
File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
img = ImageTk.PhotoImage(some_image[1])
File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
Does anyone get the same behavior when running this code? What am I doing wrong?
EDIT: Using korylprince's solution, and a bit of cleaning, the following is a working version of the original code:
import os, re, Tkinter, ImageTk
def ls_rec(direc, filter_fun=lambda a:True):
for (dirname, dirnames, fnames) in os.walk(direc):
for fname in fnames:
if filter_fun(fname):
yield os.path.join(dirname,fname)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))
imgL = []
def get_next_image(event = None):
fname = images.next()
print fname
fhandle = open(fname)
img = ImageTk.PhotoImage(file=fhandle)
fhandle.close()
imgL.append(img)
image_label.config(image=img)
top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
Edit: top.bind('<Enter>'...) actually bound the event of the mouse entering the frame, rather than user pressing Enter key. The correct line is top.bind('<Return>',...).
ImageTk.PhotoImage is not really documented properly.
You should try something like this:
#outside of functions
images = list()
#inside function
global images
with open(images[i]) as f:
img = ImageTk.PhotoImage(file=f)
images.append(img)
The reason for putting the image in the list is so that python will have a reference to it. Otherwise the garbage collector will delete the image object eventually.

Python error - OverflowError: Python int too large to convert to C long

My program gives me this error:
Traceback (most recent call last):
File "C:\Simulation\SymDialog.py", line 153, in OnPaint
self.Redraw(False)
File "C:\Simulation\SymDialog.py", line 173, in Redraw
obj.Draw(self.dc)
File "C:\Simulation\SymDialog.py", line 207, in Draw
dc.DrawCircle(self._x, self._y, self._r)
File "E:\Python\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 3391, in DrawCircle
return _gdi_.DC_DrawCircle(*args, **kwargs)
OverflowError: Python int too large to convert to C long
Method from error:
OnPaint
def OnPaint(self, event):
self.Redraw(False)
wx.GCDC(wx.BufferedPaintDC(self, self._buffer))
event.Skip()
Redraw
def Redraw(self, clear):
if clear == True: del self.drawList[:]
self.dc = wx.GCDC(wx.BufferedDC(None, self._buffer))
self.dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
self.dc.Clear()
for obj in self.drawList:
obj.Draw(self.dc)
del self.dc
Draw
def Draw(self, dc):
self.setDC(dc)
dc.DrawCircle(self._x, self._y, self._r)
How can I fix this error ?
Thanks for answers
You might be mistakenly using too large values.
Edit: Since I can't comment, what are the sizes of self._x, self._y, and self._r?

Displaying images with Tkinter

I am working on a python program that displays a series of images using Tkinter and ImageTk. I have not been able to display more than a single image. Below is a small complete program that reproduces the error. The program searches the current directly recursively for jpg files, and displays them as the uses presses Enter.
import Tkinter, ImageTk,os, re
def ls_rec(direc):
try:
ls = os.listdir(direc)
except Exception as e:
return
for f in os.listdir(direc):
fpath = os.path.join(direc, f)
if os.path.isfile(fpath):
yield fpath
elif os.path.isdir(fpath):
for f2 in iterate_dir(os.path.join(direc,f)):
yield f2
images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0
def get_next_image(event = None):
global i, img
i+=1
img = ImageTk.PhotoImage(images[i])
label.config(image=img)
label.image = img
top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
The program fails with the following traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/myuser/Projects/sample_images.py", line 1, in <module>
import Tkinter, ImageTk,os, re
File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
img = ImageTk.PhotoImage(some_image[1])
File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
Does anyone get the same behavior when running this code? What am I doing wrong?
EDIT: Using korylprince's solution, and a bit of cleaning, the following is a working version of the original code:
import os, re, Tkinter, ImageTk
def ls_rec(direc, filter_fun=lambda a:True):
for (dirname, dirnames, fnames) in os.walk(direc):
for fname in fnames:
if filter_fun(fname):
yield os.path.join(dirname,fname)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))
imgL = []
def get_next_image(event = None):
fname = images.next()
print fname
fhandle = open(fname)
img = ImageTk.PhotoImage(file=fhandle)
fhandle.close()
imgL.append(img)
image_label.config(image=img)
top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
Edit: top.bind('<Enter>'...) actually bound the event of the mouse entering the frame, rather than user pressing Enter key. The correct line is top.bind('<Return>',...).
ImageTk.PhotoImage is not really documented properly.
You should try something like this:
#outside of functions
images = list()
#inside function
global images
with open(images[i]) as f:
img = ImageTk.PhotoImage(file=f)
images.append(img)
The reason for putting the image in the list is so that python will have a reference to it. Otherwise the garbage collector will delete the image object eventually.

Categories