I have written the below code for run a python file on button click through tkinter and also displaying two button for run python file on GUI window. Now my pyhton files is working fine when click on button. But there is one issue is I want to shows error on tkinter error box whatever error shows on cmd window. If I run python scripts in cmd it shows error. But want to show on tkinter error message box. How is it possible. Below I am sharing you code.
import sys
import os
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
# Create an instance of tkinter frame
win= Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a function to show the popup message
def show_msg():
os.system('mail.py')
messagebox.showinfo("Message","Email Sent Successfully.")
def gen_certificate():
os.system('certificate.py')
messagebox.showerror("error","continuwe")
messagebox.showinfo("Message","Certificate Generated Successfully.")
# Add an optional Label widget
Label(win, text= "Welcome to MBR Admin!", font= ('Aerial 17 bold italic')).pack(pady= 30)
# Create a Button to display the message
ttk.Button(win, text= "Send Mail", command=show_msg).pack(pady= 20)
ttk.Button(win, text= "Generate Certificate", command=gen_certificate).pack(pady= 20)
win.mainloop()
I would be appreciate if anyone response my questions. Thank you
CodePudding user response:
A way is to use traceback
module from python to get more info on the error. But in your example it wont be much useful because os.system
returns 1 or 0 depending on if it failed or not(and does not trigger a traceback) but subprocess.run
is a much better option:
import traceback
try:
subprocess.run(['python.exe','certificate.py'],check=1)
messagebox.showinfo("Message","Certificate Generated Successfully.")
except Exception:
tkinter.messagebox.showerror('Error',traceback.format_exc())
Try reading this if you want to use os.system
, still
CodePudding user response:
- Your os.system('mail.py') function doesn't run the file. It accepts cmd commands. Try os.system('dir ') and it will print the files in the given directory to you in the console. You can see the list of all commands here https://ss64.com/nt/.
- To run the mail.py file, you must either use the start cmd command https://ss64.com/nt/start.html or the os module command os.startfile <https://docs.python.org/3/library/os .html#:~:text=Availability: Windows.-,os.startfile,-(path[>
- As written in a previous answer, it's better to use the subprocess module:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. os.system