I have coded a small game using python turtle, and it seems like whenever I close the turtle window manually it gives me an error, but if the game finished running and then I close it's fine. I think it has something to do with the ontimer part of the code, but I'm not sure how to fix it.
import turtle
from random import randint
wn = turtle.Screen()
circle1 = turtle.Turtle(shape = 'circle')
bullet = turtle.Turtle(shape = "circle")
bullet.ht()
bullet.speed(0)
circle1.speed(-1)
circle1.penup()
circle1.ht()
circle1.sety(-270)
circle1.st()
wn.setup(300, 600)
enemies = []
score = 0
prevscore = 1
speed = 10
for i in range(10):
p = turtle.Turtle(shape='square',visible=False)
p.speed(0)
p.penup()
p.color('blue')
x = randint(-240,240)
y = randint(180,360)
p.goto(x,y)
p.showturtle()
enemies.append(p)
def enemy_move():
global game_on
global speed
global score
global prevscore
for p in enemies:
y = p.ycor()
p.sety(y-speed)
if p.ycor() < -300 or p.distance(bullet.pos())<30:
if p.distance(bullet.pos())<30:
score += 1
p.hideturtle()
y = randint(180,360)
p.sety(y)
p.showturtle()
if circle1.isvisible() and p.distance(circle1.pos())<20:
p.hideturtle()
circle1.hideturtle()
game_on = False
wn.clear()
circle1.goto(0, 0)
circle1.write(f"Your final score is {score}", align ="center", font = ("Arial", 26, "normal"))
if game_on == True:
if score%10 == 0:
if score != prevscore:
speed += 0.5
prevscore = score
wn.ontimer(enemy_move,50)
else:
return
game_on = True
enemy_move()
def goright():
if(circle1.xcor() < 130):
circle1.seth(0)
circle1.fd(10)
def goleft():
if(circle1.xcor() > -130):
circle1.seth(180)
circle1.fd(10)
def shoot():
bullet.penup()
bullet.goto(circle1.pos())
bullet.seth(90)
bullet_move()
bullet.showturtle()
def bullet_move():
if bullet.ycor() <= 300:
bullet.sety(bullet.ycor() + 10)
wn.ontimer(bullet_move, 50)
else:
bullet.hideturtle()
wn.listen()
wn.onkeypress(goright, "Right")
wn.onkeypress(goleft, "Left")
wn.onkeypress(shoot, "Up")
wn.mainloop()
The error I get when I exit the code manually is this:
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/Class Teaching/Game interface example.py", line 1, in <module>
import game
File "/Users/luke/PycharmProjects/Class Teaching/game.py", line 31, in <module>
p.goto(x,y)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 1777, in goto
self._goto(Vec2D(x, y))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 3159, in _goto
screen._pointlist(self.currentLineItem),
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 756, in _pointlist
cl = self.cv.coords(item)
File "<string>", line 1, in coords
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2762, in coords
self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"
It is caused by the for loop inside enemy_move(). If you try to exit the application by destroying the window, the for loop may still be running and so accessing the already destroyed canvas raises the exception.
You can check game_on at the beginning of each iteration of the for loop:
def enemy_move():
...
for p in enemies:
# exit the function is game_on is False
if not game_on:
return
...
...
Then you need to set game_on to False before destroying the window. It can be done using tkinter.protocol() (as turtle is built on tkinter):
...
def on_quit():
global game_on
game_on = False
# give some time to stop the for loop before destroying window
wn._root.after(100, wn._root.destroy)
wn._root.protocol("WM_DELETE_WINDOW", on_quit)
wn.mainloop()
Related
I'm creating FPS game with Ursina Engine (python). But I started to get a error whenever I tried to play it.
I just started coding so I don't know what I should do.
Code:
from ursina import *
from ursina.prefabs.first_person_controller import *
class Player(Entity):
def __init__(self, **kwargs):
self.controller = FirstPersonController(**kwargs)
super().__init__(parent=self.controller)
self.hand_gun = Entity(parent=self.controller.camera_pivot, scale=0.1, position=Vec3(0.7, -1, 1.5), rotation=Vec3(0, 170, 0), model='gun', Texture='M1911-RIGHT', visible=False)
self.knife = Entity(parent=self.controller.camera_pivot, scale=0.4, position=Vec3(0.7, -1, 1.5), rotation=Vec3(0, 170, 0), model='knife', Texture='knife', visible=False)
self.weapons = [self.hand_gun, self.knife]
self.current_weapon = 0
self.switch_weapons()
def switch_weapon(self):
for i, v in enumerate(self.weapons):
if i == self.current_weapon:
v.visible = True
else:
v.visible = False
def input(self, key):
try:
self.current_weapon = int(key) - 1
self.switch_weapon()
except ValueError:
pass
if key == 'scroll up':
self.current_weapon = (self.current_weapon + 1) % len(self.weapons)
self.switch_weapon()
if key == 'scroll down':
self.current_weapon = (self.current_weapon - 1) % len(self.weapons)
self.switch_weapon()
if key == 'left_mouse_down' and self.current_weapon == 0:
Bullet(model='sphere', color=color.black, scale=0.2, position=self.controller.camera_pivot.world_position, rotation=self.controller.camera_pivot.world_rotation)
def update(self):
self.controller.camera_pivot.y = 2 - held_keys['left control']
class Bullet(Entity):
def __init__(self, speed=50, lifetime = 10, **kwargs):
super().__init__(**kwargs)
self.speed = speed
self.lifetime = lifetime
self.start = time.time()
def update(self):
ray = raycast(self.world_position, self.forward, distance=self.speed*time.dt)
if not ray.hit and time.time() - self.start < self.lifetime:
self.world_position += self.forward * self.speed * time.daylight
else:
destroy(self)
app = Ursina
ground = Entity(model='plane', scale=20, texture='white_cube', texture_scale='mesh')
player = Player(position=(0,10,0))
app.run()
It's just small shooting game that I made for learning Ursina Engine
and the error message I got was:
package_folder: C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina
asset_folder: c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine
Exception ignored in: <function Texture.__del__ at 0x000001E55A5129E0>
Traceback (most recent call last):
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\texture.py", line 185, in __del__ del self._cached_image
AttributeError: _cached_image
Traceback (most recent call last):
File "c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine\03 - Weapons.py", line 71, in <module>
player = Player(position=(0,10,0))
File "c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine\03 - Weapons.py", line 6, in __init__
self.controller = FirstPersonController(**kwargs)
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\prefabs\first_person_controller.py", line 32, in __init__
ray = raycast(self.world_position+(0,self.height,0), self.down, ignore=(self,))
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\entity.py", line 433, in world_position
return Vec3(self.get_position(render))
NameError: name 'render' is not defined
How can I fix it?
I think it's some kind of attribute error but I don't know what to do.
You should instantiate Ursina with app = Ursina() before instantiating Entities. You're missing the ().
So after getting inspired by code bullet to try out pyglet. Recently I have been creating many small games and simulations with it. The current one being a game is a flappy bird(Pretty sure you've all played that). So my mission is to code flappybird with pyglet today. But as usual, I fell into a problem, and even though there were many questions and answers for this problem as I was using pyglet all of the other answers weren't working.
The code I have written for the flappy bird is pretty straightforward. I have 2 classes the bird and the pipe and I render all of them using batches and groups. here:
import math, sys
import pyglet, random
from pyglet.window import key, mouse
window = pyglet.window.Window(width=335, height=540, caption="FLAPPY BIRD!")
batch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
pipes = pyglet.graphics.OrderedGroup(1)
foreground = pyglet.graphics.OrderedGroup(2)
player = pyglet.graphics.OrderedGroup(3)
bg = pyglet.image.load("background.png")
background_1 = pyglet.sprite.Sprite(bg, 0, 0, batch=batch, group=background)
background_2 = pyglet.sprite.Sprite(bg, bg.width, 0, batch=batch, group=background)
base = pyglet.image.load("base.png")
base_1 = pyglet.sprite.Sprite(base, 0, 0, batch=batch, group=foreground)
base_2 = pyglet.sprite.Sprite(base, base.width, 0, batch=batch, group=foreground)
bird_image = pyglet.image.load("yellowbird-midflap.png")
bird_image.anchor_x = bird_image.width // 2
bird_image.anchor_y = bird_image.height // 2
class Bird:
def __init__(self):
self.charector = \
pyglet.sprite.Sprite(bird_image, window.width * 0.2, window.height/2, batch=batch, group=player)
self.y_speed = 0
self.rotation_vel = 0
self.alive = True
def update(self):
self.y_speed -= 0.6
self.rotation_vel += 1
self.charector.y += self.y_speed
self.charector.rotation = min(self.rotation_vel, 90)
def jump(self):
self.y_speed = 7 * 1.5
self.rotation_vel = -35
bird_image = pyglet.image.load("yellowbird-midflap.png")
class Pipe:
tp = pyglet.image.load("down-pipe.png")
bp = pyglet.image.load("pipe.png")
def __init__(self):
self.top_pipe = pyglet.sprite.Sprite(self.tp, x = window.width + 100, y = random.randint(325, 484), batch=batch, group=pipes)
self.bottom_pipe = pyglet.sprite.Sprite(self.bp, x = window.width + 100, y = self.top_pipe.y - 125 - self.bp.height, batch=batch, group=pipes)
def update(self):
self.top_pipe.x -= 3
self.bottom_pipe.x -= 3
bird = Bird()
pipes = [Pipe()]
time_created_pipe = 50
def update_char(dt):
global time_created_pipe, pipes
if bird.alive:
bird.update()
for pipe in pipes:
pipe.update()
if pipe.top_pipe.x <= -100:
pipes.remove(pipe)
if time_created_pipe <= 0:
time_created_pipe = 50
pipes.append(Pipe())
time_created_pipe -= 1
def update_bg(dt):
if bird.alive:
background_1.x -= 0.5
background_2.x -= 0.5
if background_1.x <= -bg.width:
background_1.x = bg.width
if background_2.x <= -bg.width:
background_2.x = bg.width
base_1.x -= 1.5
base_2.x -= 1.5
if base_1.x <= -base.width:
base_1.x = base.width
if base_2.x <= -base.width:
base_2.x = base.width
#window.event
def on_mouse_press(x, y, button, modifiers):
if button == mouse.LEFT:
bird.jump()
#window.event
def on_draw():
window.clear()
batch.draw()
pyglet.clock.schedule_interval(update_char, 1/60)
pyglet.clock.schedule_interval(update_bg, 1/60)
pyglet.app.run()
But the second I run the code this happens:
back (most recent call last):
File "c:\Users\Tejas&Shiva\OneDrive\Desktop\HTCODEATHON PYTHON PRACTICE\Day4\flappy bird.py", line 105, in <module>
pyglet.app.run()
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\app\__init__.py", line 107, in run
event_loop.run()
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\app\base.py", line 169, in run
timeout = self.idle()
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\app\base.py", line 239, in idle
redraw_all = self.clock.call_scheduled_functions(dt)
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\clock.py", line 292, in call_scheduled_functions
item.func(now - item.last_ts, *item.args, **item.kwargs)
File "c:\Users\Tejas&Shiva\OneDrive\Desktop\HTCODEATHON PYTHON PRACTICE\Day4\flappy bird.py", line 73, in update_char
pipes.append(Pipe())
File "c:\Users\Tejas&Shiva\OneDrive\Desktop\HTCODEATHON PYTHON PRACTICE\Day4\flappy bird.py", line 50, in __init__
self.top_pipe = pyglet.sprite.Sprite(self.tp, x = window.width + 100, y = random.randint(325, 484), batch=batch, group=pipes)
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\sprite.py", line 246, in __init__
self._create_vertex_list()
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\sprite.py", line 391, in _create_vertex_list
self._vertex_list = self._batch.add(
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\graphics\__init__.py", line 366, in add
domain = self._get_domain(False, mode, group, formats)
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\graphics\__init__.py", line 443, in _get_domain
self._add_group(group)
File "C:\Users\Tejas&Shiva\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\graphics\__init__.py", line 468, in _add_group
if group.parent not in self.group_map:
TypeError: unhashable type: 'list'
My guess is there is a problem with the pipes list but I'm not sure why. Is there any solution to this?
The problem is that the name pipes is used twice. First is used for the OrderedGroup of pipes. In this group, the initial pipe batches are added:
pipes = pyglet.graphics.OrderedGroup(1)
However, it is then used for a list of pipes. The original group pipes is shadowed by the list of pipes and creating a new Pipe object fails:
pipes = [Pipe()]
Use different names for the group and the list. Rename list:
pipes_list = [Pipe()]
time_created_pipe = 50
def update_char(dt):
global time_created_pipe, pipes_list
if bird.alive:
bird.update()
for pipe in pipes_list:
pipe.update()
if pipe.top_pipe.x <= -100:
pipes_list.remove(pipe)
if time_created_pipe <= 0:
time_created_pipe = 50
pipes_list.append(Pipe())
time_created_pipe -= 1
I created a small game with Pygame and MU IDE. Then I wanted to convert the .py file to a .exe file with pyinstaller. It was no problem to create the exe file. But if I want to execute the created exe file I get the following error message: 'name Actor is not defined'. With MU IDE I can execute the corresponding .py file without any problems. How can I fix the problem?
The full error message is:
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "test.py", line 11, in module
NameError: name 'Actor' is not defined
[1920] Failed to execute script test
Here is the code:
from random import randint
import time
import pygame
HEIGHT = 800
WIDTH = 800
score = 0
time_left = 10
banana = Actor("banana")
monkey = Actor("monkey")
pygame.mixer.init()
pygame.mixer.music.load("music\\music.mp3")
pygame.mixer.music.play(-1)
background = pygame.image.load("images\\background.png")
def draw():
screen.blit("background",(0,0))
banana.draw()
monkey.draw()
screen.draw.text("Anzahl der gesammelten Bananen: " + str(score), color = "black", topleft=(10,10))
screen.draw.text("verbleibende Sekunden: " + str(time_left), color = "black", topleft=(10,50))
def place_graphics():
banana.x = randint(125, 790)
banana.y = randint(186, 790)
monkey.x = 50
monkey.y = 740
def on_mouse_down(pos):
global score
if banana.collidepoint(pos):
score = score + 1
place_graphics()
if monkey.collidepoint(pos):
effect = pygame.mixer.Sound("sounds\\monkey.wav")
effect.play()
def update_time_left():
global time_left
if time_left:
time_left = time_left - 1
else:
game_over()
place_graphics()
clock.schedule_interval(update_time_left, 1.0)
def game_over():
global score
screen.fill("green")
screen.draw.text("Game Over: Du hast " + str(score) + " Bananen gesammelt!", topleft=(100,350), fontsize=40)
screen.draw.text("Magst du nochmal spielen? ja [j] oder nein [n]", topleft=(150,450), fontsize=30)
pygame.display.update()
Actor is not a part of PyGame. It is a class of Pygame Zero. See Actors. Pygame Zero is based on Pygame and adds many classes to Pygame. You have to import pgzrun:
import pgzrun
Hello I'm creating a game using pygame and I had some problems. I create some buttons (using images)and depending in some actions the Image of this buttons will change.I will show you the the part of the code where there is the Error.
And sorry, but I'm Spanish, and my English is bad. This is the code:
import pygame
from pygame.locals import *
import time
pygame.init()
display_weight = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_weight, display_height), pygame.RESIZABLE)
pygame.display.set_caption("I NEED HELP :d")
clock = pygame.time.Clock()
#BUTTONS IMAGE
default_ap = pygame.image.load('button_menu_ap.png')
default_ip = pygame.image.load('button_menu_ip.png')
chewbacca_ip = pygame.image.load('button_select_GalaxyWars_chewbacca_ip.png')
chewbacca_ap = pygame.image.load('button_select_GalaxyWars_chewbacca_ap.png')
def button_img(x,y,w,h,ip,ap,action=None,especific1=None,especific2=None,especific3=None,especific4=None,especific5=None,especific6=None\
,especific7=None,especific8=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse [1] > y:
gameDisplay.blit(ap, (x,y))
if click [0] == 1 and action != None:
if especific1 != None:
if especific2 != None:
if especific2 != None and especific3 != None and especific4 != None and especific5 != None and especific6 != None \
and especific7 != None and especific8 != None:
action(especific1, especific2, especific3, especific4, especific5, especific6, especific7, especific8)
else:
action(especific1, especific2)
else:
action(especific1)
else:
action()
else:
gameDisplay.blit(ip, (x,y))
pygame.display.update()
def select_p1(nombre):
nombre_ip = (nombre + '_ip')
nombre_ap = (nombre + '_ap')
return button_img(display_weight/2-300,display_height/2-250,100,100,nombre_ip,nombre_ap,select_categoria,1,nombre)
pygame.display.update()
def select_categoria(num):
global gameDisplay, display_weight,display_height
select_categoria = True
gameDisplay.fill((255,255,255))
while select_categoria:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
# Este es el código que redimensiona la ventana
if event.type == VIDEORESIZE:
# Recrea la ventana con el nuevo tamaño
display_weight = event.w
display_height = event.h
gameDisplay = pygame.display.set_mode((display_weight, display_height),
pygame.RESIZABLE)
button_img(display_weight/2-125,display_weight/2-125,250,60,button_select_categoria_ip,button_select_categoria_ap, select_GalaxyWars, num)
pygame.display.update()
clock.tick(15)
clock.tick(15)
select_p1 ('default')
Then the Error is that one:
Traceback (most recent call last):
File "C:/Users/win/Desktop/MARCOS/PYTHON/PROYECTO HGA/HELP.py", line 73,
in <module>
select_p1 ('default')
File "C:/Users/win/Desktop/MARCOS/PYTHON/PROYECTO HGA/HELP.py", line 46,
in select_p1
return button_img(display_weight/2-300,display_height/2-
250,100,100,nombre_ip,nombre_ap,select_categoria,1,nombre)
File "C:/Users/win/Desktop/MARCOS/PYTHON/PROYECTO HGA/HELP.py", line 39,
in button_img
gameDisplay.blit(ip, (x,y))
TypeError: argument 1 must be pygame.Surface, not str
For Example in the last line of the code:
select_p1 ('default')
If I put 'default', the images be the ones call default_ap and default_ip, those ones:
default_ap = pygame.image.load('button_menu_ap.png')
default_ip = pygame.image.load('button_menu_ip.png')
And if I put chewbacca, the images will be the ones call chewbacca_ap and chewbacca_ip.
Please, is someone knows a way to solve my problem, please tell me.
The error is self explanatory:
gameDisplay.blit(ip, (x,y))
TypeError: argument 1 must be pygame.Surface, not str
The object ip should be a pygame.Surface, instead it is an str. Perhaps you want to create a dictionary:
button_image_dict = {'default_ip': default_ip,
'default_ap': default_ap,
'chewbacca_ip': chewbacca_ip,
'chewbacca_ap': chewbacca_ap}
And then use this dictionary to find the object from the string:
gameDisplay.blit(button_image_dict[ip], (x,y))
I have a dictionary of characters: cheracters = {'default':0,'chewbacca':1,'Stormsoldier':2}
First, I think that should be a list. All you're storing is item positions.
If I understand what you're trying to do, you want a dictionary for the images
For example
ap = {
'default' : 'button_menu_ap.png',
'chewbacca' : 'button_select_GalaxyWars_chewbacca_ap.png'
}
nombre = 'chewbacca'
chewbacca_ap = pygame.image.load(ap[nombre])
I know that something very basic is wrong here which I just fail to see. I'd really appreciate if somebody more experienced in Python could point out where I misunderstood things here. I post a simplified version of my code below. To trace back where the problems start, have an eye on the following:
The MainProgram, instanciated as Main = MainProgram(), has a menu (self.menu = Startmenu()) which is an instance of the Menu class. This Menu class has a list of buttons (self.buttons = [...]) - in this case only one. They are an instance of the Button class. I now need to pass the function to be triggered when the button is clicked to that instance of the Button class, so I can actually use it.
I would really be thankful to any more experienced user having a quick glance at it. I'm sure I'm failing to see something very basic. I bet I'm too tired to see it... Had only some 2 hours sleep since there's a baby in the house now :D
My code:
class MainProgram:
#Much much more code
def __init__(self):
#And so much more code here
self.menu = StartMenu()
class StartMenu:
def __init__(self):
#Much code which is not important to us here
self.buttons = [Button("d_bt_start", (100, 60)
, testfunc, "TEST-TEXT")]
class Button:
def __init__(self, image, pos = (0, 0), path = Paths.path_img
, alpha = False, func = None, args = None):
self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
self.img_hover = helper.loadImage(path, image + "_hover.jpg", alpha)
self.image = self.img_normal
self.pos = pos
self.x = pos[0]
self.y = pos[1]
self.width = self.x + self.image.get_width()
self.height = self.y + self.image.get_height()
self.mouseover = 0
self.func = func
self.args = args
def update(self, (mx, my)):
if (mx >= self.x and mx <= self.width and
my >= self.y and my <= self.height):
if self.mouseover == 0:
self.image = self.img_hover
self.mouseover = 1
else:
if self.mouseover == 1:
self.image = self.img_normal
self.mouseover = 0
def clicked(self, button):
if (mx >= self.x and mx <= self.width and
my >= self.y and my <= self.height):
if button == 1:
self.func(self.args)
What should happen: The main file creates an instance of the StartMenu class. In the StartMenu class we define one button as an instance of the Button class. That button should trigger the function testfunc(args) upon being clicked. This testfunction is so far just a print of the "TEST-TEXT" argument.
If I pass the function as
testfunc
then I get the following error Traceback:
Traceback (most recent call last):
File "D:\Python27\_RPG DEMO\DEMO\main.py", line 41, in <module>
Main = MainProgram()
File "D:\Python27\_RPG DEMO\DEMO\main.py", line 21, in __init__
self.menu = menus.StartMenu()
File "D:\Python27\_RPG DEMO\DEMO\menus.py", line 11, in __init__
, zztestfile.testfunc, "TESTEST")
File "D:\Python27\_RPG DEMO\DEMO\buttons.py", line 7, in __init__
self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
File "D:\Python27\_RPG DEMO\DEMO\helper.py", line 13, in loadImage
return pygame.image.load(os.path.join(folder, name)).convert_alpha()
File "D:\Python27\lib\ntpath.py", line 96, in join
assert len(path) > 0
TypeError: object of type 'function' has no len()
If I pass it as:
testfunc("TEST-TEXT")
it triggers but then causes the following Traceback:
TEST-TEXT
Traceback (most recent call last):
File "D:\Python27\_RPG DEMO\DEMO\main.py", line 41, in <module>
Main = MainProgram()
File "D:\Python27\_RPG DEMO\DEMO\main.py", line 21, in __init__
self.menu = menus.StartMenu()
File "D:\Python27\_RPG DEMO\DEMO\menus.py", line 11, in __init__
, testfunc("TEST-TEXT"))
File "D:\Python27\_RPG DEMO\DEMO\buttons.py", line 7, in __init__
self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
File "D:\Python27\_RPG DEMO\DEMO\helper.py", line 15, in loadImage
return pygame.image.load(os.path.join(folder, name)).convert()
File "D:\Python27\lib\ntpath.py", line 96, in join
assert len(path) > 0
TypeError: object of type 'NoneType' has no len()
I've gone through a few tutorials so far, but I really can't figure out where I'm misunderstanding them. I'd really appreciate any help in this!
You are passing your test function to the path argument of your Button class:
self.buttons = [Button("d_bt_start", (100, 60)
, testfunc, "TEST-TEXT")]
That's the 3rd positional argument there:
def __init__(self, image, pos = (0, 0), path = Paths.path_img
, alpha = False, func = None, args = None):
matching up with path. Use keyword arguments instead:
self.buttons = [Button("d_bt_start", (100, 60)
, func=testfunc, args="TEST-TEXT")]