Run a Python script by pressing a Tkinter button

Kamy_0117 Posted messages 2 Status Member -  
mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   -

Hello,

I am working on a Python project but I have a problem.

I want to open a Python program (fiher.py) with a Tkinter button, but I can't find any documentation on this topic. Any help would be wonderful for me. Thanks in advance.

The code:

from tkinter import * window = Tk() window.title("Formulate") window.geometry("1080x720") window.minsize(680, 560) window.config(background='#2AAD57') frame = Frame(window, bg='#2AAD57') label_title = Label(frame, text="Bienvenue", font=("Courrier", 40), bg='#2AAD57', fg="#FFFFFF") label_title.pack(expand=YES) label_subtitle = Label(frame, text="Formulaire de registration", font=("Courrier", 25), bg='#2AAD57', fg="#FFFFFF") label_subtitle.pack(expand=YES) play_button = Button(frame, text="Commencer", font=("Courrier", 25), bg='#FFFFFF', fg="#2AAD57") play_button.pack(pady=25,fill=X) frame.pack(expand=YES) window.mainloop() 

3 answers

yg_be Posted messages 23437 Registration date   Status Contributor Last intervention   Ambassadeur 1 588
 

Hello,

is the code you’re presenting the one from fiher.py?

0
Kamy_0117 Posted messages 2 Status Member
 

No, this code is for my graphical interface.

0
yg_be Posted messages 23437 Registration date   Status Contributor Last intervention   1 588 > Kamy_0117 Posted messages 2 Status Member
 
0
mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 940
 
Hello,

To complement yg_be's answer, the buttons in Tkinter have a parameter command that lets you call a function passed as an argument (callback).

Run another Python script
If we follow the idea proposed by ug_be It suffices that the callback launches this other Python program (for example using subprocess.call).

my_script.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print("coucou")

The file must have execute permissions. On Linux:

chmod a+x my_script.py

gui.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
from tkinter import *

def my_callback():
subprocess.call("./my_script.py", shell=True)

window = Tk()
button = Button(window, text="start", command=my_callback)
button.pack()
window.mainloop()

This file must be in the same directory as my_script.py.

Run a function defined in another Python module
It's a more elegant solution than the previous one. Indeed, we usually prefer to have a functionality wrapped in a function, which makes it easier to call and reuse. So we could modify the previous example like this:

my_lib.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def my_function():
print("coucou")

gui.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from my_lib import my_function
from tkinter import *

window = Tk()
button = Button(window, text="start", command=my_function)
button.pack()
window.mainloop()

This file must be in the same directory as my_lib.py.

Good luck
0
Nanosaure Posted messages 2 Status Member
 

grandmother, hello,

Just one clarification: if, in the first version, ./my_script.py must have arguments: how do we add them? The best would be to have fields to fill that are added automatically... But I will proceed step by step..

0
Nanosaure Posted messages 2 Status Member > Nanosaure Posted messages 2 Status Member
 

There you go, I understood: square brackets, quotation marks, and comma between each argument…

0
mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 940
 

Hello,

Regarding the messages #5 and #6 : when starting a new question, it’s a new discussion thread to keep the forum tidy.

Retrieve arguments passed to a script

The arguments passed to the script are stored in the list sys.argv; you can therefore iterate over them or use the [] operator to access a specific argument.

Example:

#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): for (i, arg) in enumerate(sys.argv): print(f"Argument {i}: '{arg}'") print(sys.argv[0]) if __name__ == "__main__": main()

Result :

python3 toto.py arg1 "arg ument 2" arg3
 Argument 0: 'toto.py' Argument 1: 'arg1' Argument 2: 'arg ument 2' Argument 3: 'arg3' toto.py

Prompt for arguments at runtime

If you want to ask for values at runtime, you first need to know how many you want to ask for. You must ask the user for this value, but since you can't be sure they will enter a positive integer, you must validate that the string they entered is valid. Then you can request the arguments based on that number.

This is what the code below does. Only the number of arguments is validated, since we have no assumption to verify about the type of the subsequent arguments. We simply store the entered string.

#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def input_int(label:str = "", test = None) -> int: while True: s = input(label) try: n = int(s) if test and test(n): return n else: print(f"Invalid input ({s})", file=sys.stderr) except ValueError as e: print(f"Invalid input ({s}): {e}", file=sys.stderr) pass def main(): num_args = input_int("Nombre d'arguments ? ", lambda x: x > 0) args = [ input(f"Argument {i + 1} ? ") for i in range(num_args) ] print(args) if __name__ == "__main__": main()

Result :

python3 toto.py
 Nombre d'arguments ? abc Saisie invalide (abc): invalid literal for int() with base 10: 'abc' Nombre d'arguments ? -2 Saisie invalide (-2) Nombre d'arguments ? 3 Argument 1 ? arg1 Argument 2 ? arg ument 2 Argument 3 ? arg3 ['arg1', 'arg ument 2', 'arg3']

Good luck

0