如何在PyQt5 GUI中添加文本框并显示OCR识别结果?
Got it, let's work through this together! Adding a text box to show your OCR results right next to the "Snap Shot" button is straightforward with Qt's layout system. Here's exactly what you need to do:
Step 1: Create the Text Box Control
First, add a text box (we'll use QLineEdit for single-line results; switch to QTextEdit if you need multi-line display) as a class member variable. This lets you access it later when updating the OCR text. You can also set it to read-only to prevent accidental edits by users.
Step 2: Adjust Layout to Group Button and Text Box
Instead of adding the "Snap Shot" button directly to your vertical layout, wrap it and the text box in a horizontal layout first. This keeps them side-by-side as you want.
Step 3: Update the Text Box with OCR Results
In your framesave method (triggered when "Snap Shot" is clicked), after extracting text with Tesseract, set that text to your new text box.
Here's the modified version of your GUI code with these changes:
# Inside your class's __init__ method layout = QtWidgets.QVBoxLayout() layout.addWidget(self.face_detection_widget) # Keep the Start button setup as before self.run_button = QtWidgets.QPushButton('Start') layout.addWidget(self.run_button) self.run_button.clicked.connect(self.record_video.start_recording) # 1. Create the OCR text box self.ocr_text_box = QtWidgets.QLineEdit() self.ocr_text_box.setReadOnly(True) # Optional: lock editing to show results only self.ocr_text_box.setPlaceholderText("OCR result will appear here...") # Optional: hint text # 2. Create a horizontal layout to group Snap Shot button and text box screenshot_row_layout = QtWidgets.QHBoxLayout() self.screenshot = QtWidgets.QPushButton('Snap Shot') screenshot_row_layout.addWidget(self.screenshot) screenshot_row_layout.addWidget(self.ocr_text_box) # Add the horizontal layout to your main vertical layout layout.addLayout(screenshot_row_layout) # Connect the Snap Shot button to your framesave method self.screenshot.clicked.connect(self.record_video.framesave) self.setLayout(layout)
Then, update your framesave method to populate the text box once you have the OCR result:
def framesave(self): # Your existing code to capture the frame and process it into 'img' # ... (your image capture/processing logic here) ... # Extract text with Tesseract (your existing line) text = pytesseract.image_to_string(img, lang='spa', config=tessdata_dir_config) # 3. Update the text box with the OCR result self.ocr_text_box.setText(text)
Quick Notes:
- If your OCR results are multi-line (like longer paragraphs), replace
QLineEditwithQTextEditand useself.ocr_text_box.setPlainText(text)instead ofsetText(). - You can style the text box further (e.g., adjust font size, add padding) using
setStyleSheet()to match your app's design.
内容的提问来源于stack exchange,提问作者Kim Bendix Petersen

