After my code prints one dot on the screen it doesn't run again. This is what it tells me in the terminal after I close the turtle screen:
Traceback (most recent call last):
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 33, in <module>
star(size, x, y, color)
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 12, in star
drawer.begin_fill()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 3322, in begin_fill
self._fillitem = self.screen._createpoly()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 497, in _createpoly
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
File "<string>", line 1, in create_polygon
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2492, in create_polygon
return self._create('polygon', args, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".!canvas"
My code is
import turtle
import random
def star(size, X, Y, color):
drawer.goto(X, Y)
drawer.color(color)
drawer.begin_fill()
drawer.circle(size)
drawer.end_fill()
hex = ["blue","red","yellow","white"]
screen = turtle.Screen()
turtle.bgcolor("black")
drawer = turtle.Turtle()
drawer.speed("fastest")
x = random.randint(-300,301)
y = random.randint(-300,301)
color = random.choice(hex)
size = random.randint(1,6)
a = 1
b = 100
while True:
if a <= b:
star(size, x, y, color)
drawer.hideturtle()
a + 1
continue
else:
break
screen.mainloop()
You have to assign the new a or use a += 1 and also move some lines inside the while loop to execute them each time:
while True:
if a <= b:
x = random.randint(-300, 301)
y = random.randint(-300, 301)
star(size, x, y, color)
drawer.hideturtle()
a += 1
continue
else:
break
screen.mainloop()
Related
I am trying to convert any .png images with a transparent background to a white background.
however I am getting an error that says tuple object is not callable.
I have tried this:
def transparent_to_white(img):
color = (255, 255, 255)
for x in range(img.size()):
for y in range(img.size()):
r, g, b, a = img.getpixel((x, y))
if a == 0:
img.putpixel((x, y), color)
return img
but I get this error:
Original Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 49, in __getitem__
y_label = self.resize(transparent_to_white(y_label))
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 33, in transparent_to_white
for x in range(img.size()):
TypeError: 'tuple' object is not callable
I am called it in my dataset class :
class Pix2PixDataset(Dataset):
def __init__(self, data_points, transforms = None):
self.data_points = data_points
self.transforms = transforms
self.resize = T.Resize((512,512))
def __getitem__(self, index) :
image, y_label = process_images(self.data_points[index].reference_image, self.data_points[index].drawing )
image = self.resize(image)
y_label = self.resize(transparent_to_white(y_label))
if self.transforms:
image = self.transforms(image)
y_label = self.transforms(y_label)
return(image, y_label)
def __len__(self):
return len(self.data_points)
I tried removing the open and close parenthesis but that did not help, I still get the same error
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 49, in __getitem__
y_label = self.resize(transparent_to_white(y_label))
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 33, in transparent_to_white
for x in range(img.size()):
TypeError: 'tuple' object is not callable
Disclaimer: I'm assuming img is an instance of Image class, from module PIL or it's fork Pillow
img.size is a tuple. For example, if you do:
print(img.size)
It prints a tuple with (width, height).
So, your code could be
def transparent_to_white(img):
color = (255, 255, 255)
width, height = img.size # unpacking width/height beforehand
for x in range(width): # using unpacked values in range
for y in range(height)): # same as above
r, g, b, a = img.getpixel((x, y))
if a == 0:
img.putpixel((x, y), color)
return img
Or, alternatively, you could store x and y into a tuple of coordinates, to simplify passing it around:
def transparent_to_white(img):
color = (255, 255, 255)
width, height = img.size # unpacking width/height beforehand
for x in range(width): # using unpacked values in range
for y in range(height)): # same as above
coords = (x, y) # tuple of coordinates
r, g, b, a = img.getpixel(coords) # used here
if a == 0:
img.putpixel(coords, color) # and here
return img
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.
I am trying to run a program in visual studio code with VPython and Python, however when I run it. The program tells me there is an AttributeError involving the 'electron' variable even though it is indeed defined in the updateAcceleration function on line 26 of my createProceduralAtom.py script. I have tried to declare 'electron' in a few different places including the init portion of the class createParticleAtom as seen in this question here: AttributeError: '' object has no attribute '', have tried to fix the indentation inside of the class itself but it's correctly indented: Why am I getting AttributeError: Object has no attribute?, and finally, I have tried to declare it as a global variable to not use the self variable that references the 'electron' variable entirely. But despite all of that none of the mentioned solutions have worked for me.
Here is the error that I am getting:
Traceback (most recent call last):
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\trevo\.vscode\extensions\ms-python.python-2022.6.3\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\Users\trevo\.vscode\extensions\ms-python.python-2022.6.3\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 444, in main
run()
File "c:\Users\trevo\.vscode\extensions\ms-python.python-2022.6.3\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 285, in run_file
runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 268, in run_path
return _run_module_code(code, init_globals, run_name,
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\trevo\OneDrive\Desktop\vegaai-master\tensor_net\simulation.py", line 4, in <module>
createParticleAtom(0, 0, 0, 1)
File "c:\Users\trevo\OneDrive\Desktop\vegaai-master\tensor_net\proceduralGeneratedExamples\createProceduralAtom.py", line 25, in __init__
self.createAtom(numberOfElectrons=1)
File "c:\Users\trevo\OneDrive\Desktop\vegaai-master\tensor_net\proceduralGeneratedExamples\createProceduralAtom.py", line 64, in createAtom
self.electron.velocity = self.electron.velocity + upAcc*dt
AttributeError: 'createParticleAtom' object has no attribute 'electron'
Here are my simulation.py and createProceduralAtom.py scripts respectively:
simulation.py:
from proceduralGeneratedExamples.createProceduralAtom import createExpandedAtom, createParticleAtom
createParticleAtom(0, 0, 0, 1)
createProceduralAtom.py:
from vpython import curve, color, vector, sphere, rate, mag, norm
import numpy as np
class createParticleAtom:
def __init__(self, x, y, z, radius, defaultPosition=vector(0,0,0), frameOn=None, electronList=[]):
super().__init__()
self.x = x
self.y = y
self.z = z
self.radius = radius
self.defaultPosition = defaultPosition
self.frameOn = frameOn
self.electronList = electronList
self.createAtom(numberOfElectrons=1)
def updateAcceleration(self):
for self.electron in self.electronList:
dr1 = self.electron.pos - self.Nucleon.pos
Force1 = 1/(4*self.pi*self.e0)*self.Nucleon.charge*self.electron.charge/mag(dr1)**2 * norm(dr1)
m1 = self.electron.mass
return Force1/m1
def createAtom(self, numberOfElectrons=None):
if self.frameOn:
listOfPoints=[vector(0, 0, 0), vector(1, 0, 0), vector(1, 1, 0), vector(0, 1, 0), vector(0, 0, 0), vector(0, 0, 1), vector(0, 1, 1), vector(0,1,0), vector(1,1,1), vector(1, 1, 0), vector(1, 0, 0), vector(1,0,1), vector(1, 1, 1), vector(0, 1, 1), vector(0, 0, 1), vector(1, 0, 1)]
vect1 = curve(pos=listOfPoints[:len(listOfPoints)//2], color=color.green)
vect2 = curve(pos=listOfPoints[len(listOfPoints)//2:], color=color.green)
self.pi = np.pi
self.a0 = 0.529177e-10
mE = 9.10938356e-31
mN = 1.6726219e-27
self.e0 = 8.854187e-12
e = 1.6021765e-19
c = 3e8
self.vE = e/np.sqrt(4*self.pi*self.e0*self.a0*mE)
self.shellLayers = [0, 1, 2, 3, 4, 5, 6]
self.Nucleon = sphere(pos = self.defaultPosition, radius = 0.1*self.a0, velocity = self.defaultPosition, mass = mN, charge = e, color = color.red)
self.shellLayers = 0
if self.shellLayers == 0:
for self.i in range(numberOfElectrons):
if self.i == 1:
self.i = sphere(pos=vector(self.a0,0,0), radius=0.02*self.a0, velocity=vector(0, self.vE,0), mass=mE, charge=-e, color=color.blue)
self.electronList.append(self.i)
elif self.i == 2:
self.i = sphere(pos=vector(-self.a0,0,0), radius=0.02*self.a0, velocity=vector(0, -self.vE,0), mass=mE, charge=-e, color=color.blue)
self.electronList.append(self.i)
upAcc = self.updateAcceleration()
t = 0
tOrbit = 2*self.pi*self.a0/self.vE
tEnd = 1000*tOrbit
dt = tOrbit/1000.
while (t<tEnd):
rate(100)
self.electron.velocity = self.electron.velocity + upAcc*dt
self.electron.pos = self.electron.pos + self.electron.velocity*dt
t = t + dt
Is there something obvious that I am missing, and if so how can I fix this error? Thank you!
Your error is in the line
self.electron.velocity = self.electron.velocity + upAcc*dt
If you see your class, you have not defined self.electron anywhere so It is giving the AttributeError: 'createParticleAtom' object has no attribute 'electron'.
You need to define it somewhere(probably in your __init__ function so that you can use it.
I've been writing a custom snake game using python, pygame, and pyopengl. I'm trying to draw a shape on the screen. However, I've stumbled upon this error:
Traceback (most recent call last):
File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\latebind.py", line 43, in __call__
return self._finalCall( *args, **named )
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Projects\python\Python_Game\src\game.py", line 35, in <module>
main()
File "F:\Projects\python\Python_Game\src\game.py", line 31, in main
game.draw_shapes()
File "F:\Projects\python\Python_Game\src\game_classes.py", line 203, in draw_shapes
f.draw()
File "F:\Projects\python\Python_Game\src\game_classes.py", line 128, in draw
shape.draw()
File "F:\Projects\python\Python_Game\src\opengl_classes.py", line 128, in draw
glVertex2fv(cosine, sine)
File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\latebind.py", line 47, in __call__
return self._finalCall( *args, **named )
File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\wrapper.py", line 689, in wrapperCall
pyArgs = tuple( calculate_pyArgs( args ))
File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\wrapper.py", line 450, in calculate_pyArgs
yield converter(args[index], self, args)
File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\arrays\arrayhelpers.py", line 115, in asArraySize
byteSize = handler.arrayByteCount( result )
AttributeError: ("'NumberHandler' object has no attribute 'arrayByteCount'", <function asArrayTypeSize.<locals>.asArraySize at 0x000002642A35DCA0>)
The console is throwing me a TypeError and an Attribute error. I'm not sure if this is due to my code or an issue with one of the libraries. I'm using Python 3.9.1, pygame 2.0.1, and PyOpenGL 3.1.5.
Here's the snippet of my script where the issue arises:
class Circle:
def __init__(self, pivot: Point, radius: int, sides: int, fill: bool, color: Color):
self.pivot = pivot
self.radius = radius
self.sides = sides
self.fill = fill
self.color = color
# Draw the shape of the circle
def draw(self):
glColor3f(self.color.r, self.color.g, self.color.b)
if self.fill:
glBegin(GL_POLYGON)
else:
glBegin(GL_LINE_LOOP)
for i in range(100):
cosine = self.radius * cos(i*2*pi/self.sides) + self.pivot.x
sine = self.radius * sin(i*2*pi/self.sides) + self.pivot.y
glVertex2fv(cosine, sine)
glEnd()
The argument of glVertex2fv must be an array with 2 elements. If you have two separate coordinates which are not aggregated in an array you must use glVertex2f. See glVertex:
glVertex2fv(cosine, sine)
glVertex2f(cosine, sine)
I have the following code and error message. Something I am doing seems to be messing up the % function in the hb function. I'm not really sure what or how to fix it. Any ideas?
def h(n):
if (n % 4 >= 0) and (n % 4 < 1):
k = 1
else:
k = 0
return k
def hb(n):
if (((n/4) % 2) >= 0) and (((n/4) % 2) < 1):
k = -1*h(n)
else:
k = h(n)
return k
def dalembert(y,t):
x = 0.5*hb(y-t)+0.5*hb(y+t)
return x
import numpy as np
box1 = np.array([1,2,6,10,20])
for i in range(len(box1)):
g=Graphics()
g += plot(dalembert(x,box1[i]), (x, 0, 4), color='blue')
g.show()
Error in lines 18-21
Traceback (most recent call last):
File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1188, in execute
flags=compile_flags) in namespace, locals
File "", line 3, in
File "", line 2, in dalembert
File "", line 2, in hb
File "sage/structure/element.pyx", line 1925, in sage.structure.element.Element.mod (build/cythonized/sage/structure/element.c:13956)
return coercion_model.bin_op(left, right, mod)
File "sage/structure/coerce.pyx", line 1182, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (build/cythonized/sage/structure/coerce.c:9827)
return PyObject_CallObject(op, xy)
File "sage/structure/element.pyx", line 1923, in sage.structure.element.Element.mod (build/cythonized/sage/structure/element.c:13921)
return (left).mod(right)
File "sage/structure/element.pyx", line 1958, in sage.structure.element.Element.mod (build/cythonized/sage/structure/element.c:14242)
raise bin_op_exception('%', self, other)
TypeError: unsupported operand parent(s) for %: 'Symbolic Ring' and 'Symbolic Ring'
Try replacing
g += plot(dalembert(x,box1[i]), (x, 0, 4), color='blue')
with something like
function d0(y):
return dalembert(y,box1[i]);
g += plot(d0, (x, 0, 4), color='blue')
The problem is that when you write dalembert(x,box1[i]) in your code, it is evaluated first before even getting to using that in a plot, and it's evaluated with x a symbolic, which breaks other things...