Coyney22
Coyney22

Reputation: 21

How to execute a Python 3 program in Tkinter with one button

I am trying to execute a python 3 file from tkinter when I click a button

tkinter code

import tkinter as tk
import subprocess as sub

WINDOW_SIZE = "600x400"

root = tk.Tk()
root.geometry(WINDOW_SIZE)

tk.Button(root, text="Create Motion!", command=lambda: sub.call('home/pi/motion1.py')).pack()

But getting errors when I run the program

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
    return self.func(*args)
  File "/home/pi/AnimationGUI.py", line 11, in <lambda>
    tk.Button(root, text="Create Motion!", command=lambda: sub.call('motion1.py')).pack()
  File "/usr/lib/python3.5/subprocess.py", line 247, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'motion1.py'

Upvotes: 2

Views: 832

Answers (2)

Sofo MEHR_
Sofo MEHR_

Reputation: 15

You can use exec() in a function as you call the button's command.

You should avoid using lambda and just use a regular function.

Also, to make sure the file gets closed, just wrap a with block around exec()

from tkinter import * 
window = Tk()
window.geometry("100x100")
window.title('Run another program')

def runsomething():
    with open("yourpathhere.py") as file:
       exec(open("thesamepathhere.py").read()) # exec() in python 3 is the equivalent of execfile() in python 2 #


btn = Button(window, text = "Run a program", command=runsomething)
btn.pack()


window.mainloop()

Upvotes: 0

Novel
Novel

Reputation: 13729

You are doing it all wrong. The proper way to do this is to make "motion1.py" with a function in it that does something. Let's say you call that function "main" (very common). Then your code would be:

import tkinter as tk
import motion1

WINDOW_SIZE = "600x400"

root = tk.Tk()
root.geometry(WINDOW_SIZE)

btn = tk.Button(root, text="Create Motion!", command=motion1.main)
btn.pack()

Assuming that your code and "motion1.py" are in the same folder.

Upvotes: 1

Related Questions