RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
proffessor17
Asked: 2025-02-18 22:04:47 +0000 UTC

执行 os.system('python myscript.py') 时出现错误 ModuleNotFoundError

  • 6
def paint():
    os.system('python paint.py')

基本上,使用上面的代码片段,我从另一个代码中运行我需要的代码,paint.py 导入了几个库:


import math
import time
import cv2
import mediapipe as mp
import numpy as np

当我运行 paint.py 代码时,它可以工作,但是当我用第一段代码运行它时,它会抛出一个错误


  File "F:\.....\Smart\paint.py", line 4, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'

尽管我已经安装好了所有东西,但是可能存在什么问题?蟒蛇3.11;赢 10。

python
  • 2 个回答
  • 64 Views
Martin Hope
Евграф Котовский
Asked: 2025-02-18 17:23:07 +0000 UTC

PyQt5 中 QLabel 中的文本超出范围

  • 6

我为fb2书籍编写了这个阅读器,见下文。

当我将列表中的文本粘贴pages[]到 时textLabel,
文本“超出”了 的宽度textLabel。

在此处输入图片描述


setWordWrap这有帮助,但是文本变得难以阅读。

在此处输入图片描述

没有的话该如何修复setWordWrap?


main.py:

import sys
from config import *
from PyQt5.Qt import *
from src.Book import *
from src.styles.WhiteTheme import *


class BookViewer(object):
    def __init__(self, appStyle: style = WhiteTheme, appStyleFromSystem="Windows",
                 app=QApplication(sys.argv)) -> None:

        self.app = app
        self.Book = None

        # creating and configuring BookViewer window
        self.content = QWidget()
        self.content.setFixedSize(500, 500)
        self.content.setWindowIcon(QIcon("./media/karfagen.png"))
        self.content.setWindowTitle(f"Karfagen Book Viewer")
        self.content.setStyleSheet(appStyle.style)
        self.text_font = QFont(FONT_NAME, TEXT_SIZE)
        self.text_height = QFontMetrics(self.text_font)

        self.layout = QVBoxLayout(self.content)

        self.pageNumber = 0

        self.textLabel = QLabel()
        self.textLabel.setFixedWidth(400)
        self.textLabel.setFixedHeight(400)

        self.navigationBox = QGroupBox()
        self.navigationBox.setStyleSheet("""
        QGroupBox {
            border: 0px black solid;
        }
        """)

        #creating navigation panel
        self.navigationTopPanel = QWidget()
        self.navigationTopPanelLayout = QHBoxLayout()
        self.navigationTopPanel.setLayout(self.navigationTopPanelLayout)

        self.openFile = QPushButton(text = "open file")
        self.openFile.clicked.connect(self.openFileFunc)
        self.openFile.setFixedWidth(70)

        self.layout.addWidget(self.navigationTopPanel)

        self.navigationTopPanelLayout.addWidget(self.openFile)
        self.navigationTopPanelLayout.setAlignment(Qt.AlignLeft)

        #creating elements for navigation in Book
        self.navigationBoxLayout = QHBoxLayout()

        self.btn_prev = QPushButton(text="<")
        self.btn_prev.clicked.connect(self.prev_page)

        self.pageNumberLabel = QLabel(text=str(self.pageNumber))

        self.btn_next = QPushButton(text=">")
        self.btn_next.clicked.connect(self.next_page)

        self.navigationBoxLayout.addWidget(self.btn_prev)
        self.navigationBoxLayout.setAlignment(Qt.AlignCenter)
        self.navigationBoxLayout.addWidget(self.pageNumberLabel)
        self.navigationBoxLayout.addWidget(self.btn_next)

        self.navigationBox.setLayout(self.navigationBoxLayout)

        self.layout.addWidget(self.textLabel)
        self.layout.addStretch()
        self.layout.addWidget(self.navigationBox)
        self.content.setLayout(self.layout)

    def start(self):
        self.content.show()
        self.app.exec_()

    def render_page(self, pageNumber):
        try:
            self.pageNumberLabel.setText(str(pageNumber + 1))
            self.textLabel.setText("".join(self.pages[self.pageNumber]))
        except Exception as e:
            self.show_messagebox(str(e))

    def prev_page(self):
        if self.pageNumber > 0 and self.Book:
            self.pageNumber -= 1
            self.render_page(self.pageNumber)

    def next_page(self):
        if self.pageNumber <= len(self.pages) and self.Book:
            self.pageNumber += 1
            print(self.pageNumber)
            self.render_page(self.pageNumber)

    def parseBookData(self):
        """
        Parses raw book data into pages, handling paragraph wrapping and page breaks.

        Returns:
            A list of pages, where each page is a list of strings (paragraphs/lines).
        """

        pages= []
        page = []
        current_text_height = 0
        font_metrics = QFontMetrics(QFont(FONT_NAME, TEXT_SIZE))

        for paragraph in self.Book.text_data:
            # Split paragraph into lines that fit
            lines = self.split_paragraph_into_lines(paragraph, font_metrics, self.textLabel.width())
            for line in lines:
                line_height = font_metrics.height()  # Use actual line height

                if current_text_height + line_height <= self.textLabel.height():
                    page.append(line + "<br>")
                    current_text_height += line_height
                else:
                    pages.append(page)
                    page = [line]
                    current_text_height = line_height  # Reset height to the current line's height

        # Add the last page if it's not empty
        if page:
            pages.append(page)

        return pages

    def split_paragraph_into_lines(self, paragraph: str, font_metrics: QFontMetrics, max_width: int):
        """
        Splits a paragraph into lines that fit within the maximum width, handling word wrapping.

        Args:
            paragraph: The paragraph to split.
            font_metrics: QFontMetrics object.
            max_width: The maximum width for a line.

        Returns:
            A list of strings, where each string is a line.
        """

        if font_metrics.horizontalAdvance(paragraph) >= self.textLabel.width():

            words = paragraph.split()
            lines = []
            current_line = ""

            for word in words:
                test_line = current_line + word + " "  # Add word and a space to test
                if font_metrics.horizontalAdvance(test_line) <= max_width:
                    current_line = test_line
                else:
                    if current_line:  # Add the current line if it's not empty
                        newString = ""
                        for i in range(len(current_line)):
                            newString += current_line[i]
                            if font_metrics.horizontalAdvance(newString) == max_width:
                                break
                    lines.append(newString)
                    current_line = word + " " + current_line[i:len(current_line)]  # Start a new line with the current word

            if current_line:  # Add the last line
                lines.append(current_line.strip())
            return lines

        else:
            return [paragraph]

    def openFileFunc(self):
        options = QFileDialog.Options()

        # Get the file names from the dialog
        files, _ = QFileDialog.getOpenFileNames(self.content,
                                                 "Select Fiction Book Files",
                                                 "",
                                                 "Fiction Book 2 (*.fb2);;All Files (*)",
                                                 options=options)
        if files:
            self.Book = Book(files[0])
            self.Book.parse()

            self.content.setWindowTitle(self.Book.title + " " + self.Book.author + " " + "Karfagen Book Viewer")
            self.pages = self.parseBookData()
            self.render_page(self.pageNumber)

    def show_messagebox(self, text):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Icon.Error)
        msg.setText(text)
        msg.setInformativeText("")
        msg.setWindowTitle("error")
        msg.setDetailedText("")
        msg.exec()

Book.py:

from xml.dom.minidom import parse

class Book(object):

    def __init__(self, filename, encoding="UTF-8"):
        self.filename = filename
        self.encoding = encoding

        self.text_data = None
        self.document = None

        self.genre = None
        self.author = None
        self.title = None
        self.lang = None

    def parse(self):
        document = parse(self.filename)

        self.document = document
        self.genre = self.loadTagValueFromXML("genre")
        self.lang = self.loadTagValueFromXML("lang")
        self.author = self.loadTagValueFromXML("last-name") + self.loadTagValueFromXML("first-name")
        self.title = self.loadTagValueFromXML("book-title")

        paragraphs = document.getElementsByTagName("section")
        for paragraph in paragraphs:
            text_nodes = [
                node.childNodes[0].nodeValue for node in paragraph.childNodes
                if node.nodeName == 'p' and node.childNodes[0].nodeValue
            ]
        self.text_data = text_nodes
        self.parsedTextData = []

    def loadTagValueFromXML(self, tag_name):
        try:
            tag = self.document.getElementsByTagName(tag_name)[0].childNodes[0].nodeValue
            return tag
        except IndexError:
            return ""
python
  • 1 个回答
  • 66 Views
Martin Hope
Никита
Asked: 2025-02-18 16:23:07 +0000 UTC

Sass:@use 抛出错误,未定义变量

  • 4

在我的样式表文件夹中有一个main.scss文件,所有样式都通过@use导入到其中!

@charset "UTF-8";

// 1. Vendors
@use 'vendors/reset';

// 2. Base stuff
@use 'base/base';
@use 'base/fonts';

// 3. Layout-related sections
@use 'layout/header';
@use 'layout/footer';

// 4. Components

// 5. Pages
@use 'pages/home';

// 6. Themes

并且它们被编译到css文件夹中的main.css文件中,但是我不明白为什么在编译过程中,程序拒绝了当前包含带有颜色的变量的_base.scss文件。

// COLORS
$black: #121214;
$white: #FFFFFF;
$light_gray: #8C8F96;
$dark_gray: #303030;
$blue: #49D0FF;

并给出编译错误

Compilation Error
Error: Undefined variable.
   ╷
10 │     background: $black;
   │                 ^^^^^^

通过我在 _header.scss 文件中指定的变量

.header {
  display: flex;
  height: clamp(80px, 10vw + 60px, 100px);
  background: $black;
}

尝试过:

  • 在 _header.scss 文件本身中,也写入@use '../base/base';
  • 在main.scss文件中,注册@use 'base/base' as b;并引用_header.scss来background: b.$black;..此时一般说的是没有名为“b”的模块。
  • @use 'base/base' as *;也没什么帮助。
  • 我发现了一个有类似问题的问题,问题出在旧的 Live Sass 编译器上,我检查了一下,我已经安装了新的。

只有当您将其写入 _header.scss 文件中时它才有效@import '../base/base';,但那时您不需要 main.scss...

请帮帮我,告诉我我做错了什么......

我附加了一个包含该应用程序完整结构的链接:https://codesandbox.io/p/github/KitVitalevich/XWEAR/main? file=%2Fstylesheets%2Fmain.scss%3A11% 2C22!

css
  • 1 个回答
  • 26 Views
Martin Hope
DD Alter
Asked: 2025-02-18 15:12:50 +0000 UTC

Swagger 中的授权不起作用

  • 4

我正在为一个宠物项目编写 API fastapi,问题如下 - 我正在 swagger 中并通过 post 请求测试授权:注册、授权工作。然后,我添加了工作JWT,以及依赖注入(我认为这就是它的名字)并且它再次通过 api 工作。当我尝试通过下面的按钮通过 swagger 登录时,问题就开始了:

在此处输入图片描述

它要求输入登录名和密码。问题在于数据库中的用户登录名和密码不匹配。相反,会返回一个错误:

在此处输入图片描述

我尝试将端点从 /auth/login 更改为 /login,现在收到错误:

在此处输入图片描述

神经网络表示验证似乎没有通过(但它确实通过了请求)。接下来是代码

依赖项.py:

from fastapi import HTTPException, Security
from fastapi.security import OAuth2PasswordBearer
from utils.auth import verify_token


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")


# проверка на вшивость (авторизован чел или нет)
def get_current_user(token: str = Security(oauth2_scheme)):
    # получение текущего пользователя на основе JWT
    payload = verify_token(token)
    if payload is None:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return payload

身份验证.py:

from datetime import datetime, timedelta
from jose import JWTError, jwt
from dotenv import load_dotenv
import os


load_dotenv()

SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = os.getenv("ALGORITHM")
ACCESS_TOKEN_EXPIRE = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")


# создание JWT токена
def create_access_token(data: dict, expires_delta: timedelta = None):
    """Create JWT token"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now() + expires_delta
    else:
        expire = datetime.now() + timedelta(minutes=ACCESS_TOKEN_EXPIRE)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


# проверка JWT токена
def verify_token(token: str):
    """Check JWT token"""
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except JWTError:
        return None

身份验证路由器.py:

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from database.session import SessionLocal
from database.crud import create_user, get_user_by_username
from schemas.user_scheme import UserCreate, UserLogin
from utils.security import hash_password, verify_password
from utils.auth import create_access_token
from datetime import timedelta


router = APIRouter()


async def get_session():
    async with SessionLocal() as session:
        yield session


@router.post("/register", response_model=UserCreate, tags=["Authentication"])
async def register_user(user: UserCreate,
                        session: AsyncSession = Depends(get_session)):
    existing_user = await get_user_by_username(session, user.username)
    if existing_user:
        raise HTTPException(status_code=400,
                            detail="Username already registered")

    hashed_password = hash_password(user.hashed_password)
    new_user = await create_user(session,
                                 user.username, 
                                 hashed_password,
                                 user.email)
    return new_user


@router.post("/login", tags=["Authentication"])
async def login_user(user: UserLogin,
                     session: AsyncSession = Depends(get_session)):
    db_user = await get_user_by_username(session, user.username)
    if not db_user:
        raise HTTPException(status_code=400, detail="User does not exist")

    if not verify_password(user.password, db_user.hashed_password):
        raise HTTPException(status_code=400, detail="Incorrect password")

    # JWT
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(
        data={"sub": db_user.username},
        expires_delta=access_token_expires
    )

    return {"access_token": access_token, "token_type": "bearer"}

用户方案:

from pydantic import BaseModel, EmailStr


# база для внесения в бд
class UserBase(BaseModel):
    username: str
    email: EmailStr


# создание пользователя /crud.py create_user
class UserCreate(UserBase):
    hashed_password: str | int


# обновление данных пользователя /crud.py update_user
class UserUpdate(UserBase):
    hashed_password: str | int


# удаление пользователя по id /crud.py delete_user
class UserDelete(BaseModel):
    detail: str


# вход в аккаунт /auth_router.py login_user
class UserLogin(BaseModel):
    username: str
    password: str


# модель для ответа на запросы по
# получению всех пользователей /crud_router.py get_users
class User(UserBase):
    id: int

    class Config:
        orm_mode = True

嗯,这是文件的一般结构:

│   database.db
│   main.py
│   __init__.py
│
├───database
│   │   crud.py
│   │   session.py
│   │   __init__.py
│   │
│   └───__pycache__
│           crud.cpython-311.pyc
│           session.cpython-311.pyc
│           __init__.cpython-311.pyc
│
├───models
│   │   base.py
│   │   portfolio.py
│   │   __init__.py
│   │
│   └───__pycache__
│           base.cpython-311.pyc
│           portfolio.cpython-311.pyc
│           __init__.cpython-311.pyc
│
├───routers
│   │   auth_router.py
│   │   crud_router.py
│   │   index_router.py
│   │   __init__.py
│   │
│   └───__pycache__
│           auth_router.cpython-311.pyc
│           crud_router.cpython-311.pyc
│           endpoints.cpython-311.pyc
│           index_router.cpython-311.pyc
│           __init__.cpython-311.pyc
│
├───schemas
│   │   user_scheme.py
│   │   __init__.py
│   │
│   └───__pycache__
│           user_scheme.cpython-311.pyc
│           __init__.cpython-311.pyc
│
├───static
│       .gitkeep
│
├───templates
│   │   .gitkeep
│   │   
│   └───authorisation
│           autorisation.html
│
├───tests
│       test_jwt.py
│
├───utils
│   │   auth.py
│   │   dependencies.py
│   │   security.py
│   │   __init__.py
│   │
│   └───__pycache__
│           auth.cpython-311.pyc
│           dependencies.cpython-311.pyc
│           security.cpython-311.pyc
│           __init__.cpython-311.pyc
│
└───__pycache__
        main.cpython-311.pyc
        __init__.cpython-311.pyc
python
  • 1 个回答
  • 23 Views
Martin Hope
user689495
Asked: 2025-02-18 14:46:28 +0000 UTC

如何在 tkinter python 中使文本自动调整高度?请帮忙!

  • 5

这里有一个例子:窗口上有一个文本小部件。它的行高 = 1。我输入一些内容并到达末尾,之后文本的高度立即变为 2,并且文本有足够的空间来容纳。如果我删除字符并且行太多,高度就会降低。选择和删除、Ctrl-x 和其他更改时也应该同样有效。我尝试过并使用 chat-GPT 进行斗争,但效果并不好。

python
  • 1 个回答
  • 25 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5