[英]How to Display python script Error in Tkinter message box
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.我已经编写了以下代码,用于通过 tkinter 单击按钮运行 python 文件,并在 GUI 窗口上显示两个用于运行 python 文件的按钮。 Now my pyhton files is working fine when click on button.现在我的 pyhton 文件在单击按钮时工作正常。 But there is one issue is I want to shows error on tkinter error box whatever error shows on cmd window.但是有一个问题是我想在 tkinter 错误框中显示错误,无论 cmd 窗口上显示什么错误。 If I run python scripts in cmd it shows error.如果我在 cmd 中运行 python 脚本,它会显示错误。 But want to show on tkinter error message box.但想在 tkinter 错误消息框上显示。 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谢谢
A way is to use traceback
module from python to get more info on the error.一种方法是使用 python 中的traceback
模块来获取有关错误的更多信息。 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:但是在您的示例中,它不会很有用,因为os.system
返回 1 或 0 取决于它是否失败(并且不会触发回溯),但subprocess.run
是一个更好的选择:
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如果您想使用os.system
,请尝试阅读此内容,仍然
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; subprocess 模块提供了更强大的工具来生成新进程并检索它们的结果; 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 操作系统
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.