Python Forum

Full Version: Running another python file from code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import turtle as tl
import os

home = tl.Screen()
home.bgcolor("black")
home.title("Home Screen")

lastlevel = 1
start = tl.Turtle()
start.color("green")
start.shape("square")

def startlevel(x,y):
    global lastlevel
    s = "Level %s.py" % lastlevel
    os.system(s)
    return
    
start.onclick(startlevel)

tl.mainloop()
This is my code, the other python file (Level 1.py) works perfectly fine. When i press on the turtle, a screen flickers on for just a moment and than disappears. Can you help me make this work?
First of all, you shouldn't use global. You should pass that as a parameter. Of course onclick requires a function with two parameters. So I would either do this as a class, or find another way to start your game.

Second, that's not how you run python code. You should make level 1.py a file that can be imported (really you just need to change the name). It should have a function that can be run, or a class that can be instantiated.