def start(): global img, pre_pts try: root = tk.Tk() root.withdraw() f_path = filedialog.askopenfilename() if not f_path: messagebox.showinfo('提示', '请选取有效图片') else: img = cv.imread(f_path) pre_pts = -1, -1 cv.namedWindow('picture', cv.WINDOW_NORMAL) cv.resizeWindow('picture', 256, 256) cv.moveWindow('picture', 600, 300) cv.imshow('picture', img) cv.setMouseCallback('picture', draw) cv.waitKey(0) cv.destroyAllWindows() root.destroy() except Exception as e: print("出现错误:", e) 报错后如何修改可以使下面主界面可以重新点击执行start函数,且这个start函数和主界面不在同一个py文件中:class Faceshow(QMainWindow, Ui_MainWindow): def init(self, parent=None): super(Faceshow, self).init(parent) self.setupUi(self) self.main_button.clicked.connect(start)
时间: 2023-06-13 09:08:27 浏览: 174
JavaScriptS1.rar_.CHM_JavaScriptS1_chm_java chm_pts
你可以将 start 函数放到一个单独的 py 文件中,然后在主界面中引入该文件并调用 start 函数。如果 start 函数出现错误,可以在 except 分支中添加代码,将错误信息显示在界面上,让用户知道发生了什么错误。另外,你可以在 start 函数执行完成后,手动将界面设置为可点击状态,让用户可以再次点击执行该函数。以下是修改后的代码示例:
start.py 文件:
```python
import cv2 as cv
import tkinter as tk
from tkinter import filedialog, messagebox
img = None
pre_pts = None
def draw(event, x, y, flags, param):
global img, pre_pts
if event == cv.EVENT_LBUTTONDOWN:
if pre_pts == (-1, -1):
pre_pts = x, y
else:
cv.rectangle(img, pre_pts, (x, y), (0, 255, 0), 2)
cv.imshow('picture', img)
pre_pts = -1, -1
def start():
global img, pre_pts
try:
root = tk.Tk()
root.withdraw()
f_path = filedialog.askopenfilename()
if not f_path:
messagebox.showinfo('提示', '请选取有效图片')
else:
img = cv.imread(f_path)
pre_pts = -1, -1
cv.namedWindow('picture', cv.WINDOW_NORMAL)
cv.resizeWindow('picture', 256, 256)
cv.moveWindow('picture', 600, 300)
cv.imshow('picture', img)
cv.setMouseCallback('picture', draw)
cv.waitKey(0)
cv.destroyAllWindows()
root.destroy()
return True
except Exception as e:
print("出现错误:", e)
messagebox.showerror('错误', str(e))
return False
```
主界面文件:
```python
from PyQt5.QtWidgets import QMainWindow
from PyQt5.uic import loadUi
from start import start
class Faceshow(QMainWindow):
def __init__(self, parent=None):
super(Faceshow, self).__init__(parent)
loadUi('main.ui', self)
self.main_button.clicked.connect(self.handle_start)
def handle_start(self):
if start():
# 执行成功
self.setEnabled(True)
else:
# 执行失败
self.setEnabled(False)
```
阅读全文