TangerCity
TangerCity

Reputation: 845

How to run a python script with a tkinter button?

I have a python file named main.py which looks like this:

print('hello world')

I also have a tkinkter_run.py file which looks like this:

import sys
import os
from tkinter import *
import main

window=Tk()

window.title("Running Python Script")
window.geometry('550x200')

def run():
    os.system('main.py')

btn = Button(window, text="Run your Code!", bg="blue", fg="white",command=run)
btn.grid(column=0, row=0)

window.mainloop()

When I run my tkinker_run.py file I do get a window with a Run your Code! button, however when I click that button and look the my terminal in Visual Code I get the following error:

Hello World
'main.py' is not recognized as an internal or external command,
operable program or batch file.

So it seems that Hello World is printed before I even click the Run your Code! button. I dont understand what the problem is....

Upvotes: 1

Views: 4414

Answers (2)

TangerCity
TangerCity

Reputation: 845

My directory name contains spaces, most shells split up the arguments by assuming they are separated by spaces. So the solution is to place the part that contains the filename of the script between double quotes.

os.system('python "c:\data\EK\Desktop\Python Microsoft Visual Studio\MM\main.py"')

This worked!

Upvotes: 1

user14339485
user14339485

Reputation:

This is because os.system only accepts a command and not a filename.

You can replace this code

os.system("main.py")

Like this

os.system("python main.py")

Upvotes: 0

Related Questions