Search code examples
pythontkinterbuttonprogram-entry-point

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....


Solution

  • 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!