我有一个条形码(字体 EanBwrP36Tt):
更准确地说,它是通过解析 Excel 文件获得的值(使用 openpyxl 库):
%!50BJ1F-idjbai!
我需要来自:%!50BJ1F-idjbai! -获取-2501915839108
我用谷歌搜索的所有内容,Python 库都提供下载图像作为源,但这不适合我。
是否可以使用Python获取我需要的值?
我正在 js 中生成日历,但无法从正确按下的按钮中获取值。
发电机功能:
function createInfoOnWidget (...) {
...
for (i = 1; i < lenCalRow; i++) {
var rowCal = calendarRow[i];
for (n = 1; n <= 7; n++) {
let div = document.createElement('div');
let but = document.createElement('button');
but.className = 'calendar';
if (count_past < firstDayMonth) {
div.textContent = countDaysPastMonth;
but.value = countDaysPastMonth;
count_past++;
countDaysPastMonth++;
} else {
if (count <= countCurMonthDays) {
div.textContent = count;
but.value = count;
but.onclick = (e) => { console.log(e.target.value) };
count++;
} else {
div.textContent = count_fut;
but.value = count_fut;
count_fut++;
};
}
but.appendChild(div);
rowCal.appendChild(but);
};
};
calendarButDate = document.querySelectorAll('.calendar');
};
• 我尝试通过向每个创建的按钮添加一个功能来获取数据 - 有些按钮显示值,有些则不显示。• 尝试通过函数获取数据:
$(document).ready(function () {
let calendarButDate = document.querySelectorAll('.calendar_widget__body_day_date');
...
calendarButDate.forEach( btnDate => {
btnDate.addEventListener('click', f)
});
function f(e) {
console.log(e.target.value);
};
});
它有效 - 再次部分地,当我更改小部件中的月份时,例如 - 它被重建 - 值改变, forEach 数据没有到达。
任务:能够通过单击访问每个单独生成的 id =“video”的元素。
当页面加载时,我使用 js 脚本在循环中创建元素:
const parent_widget = document.getElementById("video_block");
let create_widget_video = function() {
file.forEach(function(url) {
var div = document.createElement("div");
div.className = "video";
parent_widget.appendChild(div);
});
元素已创建,没有任何问题。同时加载了js,按照我的逻辑,应该通过id访问元素并执行特定的功能:
$(document).ready(function() {
$('.video').click( function(event){ ...
但这不会发生,我是 js 新手,如果我理解正确的话,第二个脚本根本看不到第一个脚本生成的元素,也无法在源 html 中按 id 找到元素。问题 - 如何访问在 1 个脚本中创建的每个元素?您可能可以直接在第一个脚本的循环内附加一个函数..但这已经是更高的魔法,我需要您的帮助。
ps 如果我在 html 中,我会添加几个测试元素:
<div id="video_block">
<div class="video" style="border: 1px solid #000;"></div>
<div class="video" style="border: 1px solid #000;"></div>
</div>
我有一个小部件,当您将鼠标悬停时,它会从折叠状态展开,而当您将鼠标移开时,它会返回到其原始状态。如果光标位于某个元素上,则它不应返回到其原始状态。如何正确使用对焦?
.top_line_widget {
display: flex;
padding: 3px 460px;
}
.search {
display: flex;
background: #2f3640;
height: 40px;
border-radius: 40px;
padding: 5px;
}
.search_btn {
width: 40px;
height: 40px;
border-radius: 50%;
background: #2f3640;
display: flex;
justify-content: center;
align-items: center;
transition: 0.4s;
color: #ffffff;
cursor: pointer;
}
.search_text {
border: none;
background: none;
outline: none;
padding: 0;
color: #ffffff;
font-size: 12px;
transition: 0.4s;
line-height: 40px;
width: 0px;
font-width: bold;
}
.search:hover>.search_text {
width: 910px;
padding: 0 6px;
}
.search:hover>.search_btn:hover {
background: linear-gradient(45deg, #ffa500, #ff2400);
}
<div class="top_line_widget">
<div class="search">
<input type="text" class="search_text" placeholder="Введите имя или фамилию" />
<img class="search_btn" src=".\static\images\phone_book.png">
</div>
</div>
我尝试通过将其添加到 CSS 来解决该问题 - 但没有成功:
.search:focus > .search_text{
width:910px;
padding: 0 6px;
}
如何从PyQT5 / PyQT6QLineEdit
中动态生成的文本获取文本?
我只能从最后创建的小部件中提取文本,但我想检查所有创建的小部件并提取所有不为空的数据 - 并将数据排列到列表中。QLineEdit
这是一个最低限度可重现的示例:
import sys
from PyQt6.QtWidgets import QWidget, QApplication, QGridLayout, QHBoxLayout, QPushButton, QLineEdit
class Main(QWidget):
def __init__(self):
super().__init__()
self.row_counter = 0
self.le = ''
self.grid = QGridLayout()
self.grid_line_url = QGridLayout()
self.grid.addLayout(self.generate_line_url(), 0, 0)
self.grid.addWidget(self.push_button(name='ok!',
do=self.text_from_line_edit), 1, 0)
self.setLayout(self.grid)
def h_box(self, *args):
box = QHBoxLayout()
if args:
for widget in args:
box.addWidget(widget)
return box
def push_button(self, width=None, height=None, name=None, do=None):
but = QPushButton()
if width is not None and height is not None:
but.setFixedSize(width, height)
if name:
but.setText(name)
if do:
but.clicked.connect(do)
return but
def line_edit(self):
self.le = QLineEdit()
self.le.setFixedHeight(30)
return self.le
def generate_line_url(self):
self.grid_line_url.addLayout(self.h_box(self.line_edit(),
self.push_button(width=30,
height=30,
name='+',
do=self.generate_line_url)), self.row_counter, 0, 1, 3)
self.row_counter += 1
return self.grid_line_url
def text_from_line_edit(self):
print(self.le.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec())
问题是:如何在前一个函数完成后启动一个函数。
函数中的函数,但具有计算出第一个函数的强制条件。
任务是拍照并在 GUI 中显示。
我尝试使用它Thread
(我也尝试过Thread + signal
- 唯一的选择是通过Thread
第一个任务启动,该任务emit
完成后发送一个信号来启动第二个任务,它可以工作,但长时间运行会导致错误和应用程序冻结) 。
我尝试单独使用信号,但我已经在寻找async
/ await
,但我找不到简单但有效的解决方案。
我将不胜感激任何帮助。
最小可重现示例:
import fnmatch
import os
import sys
import threading
import time
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtMultimedia import QCamera, QCameraViewfinderSettings, QCameraImageCapture, QCameraInfo
from PyQt5.QtMultimediaWidgets import QCameraViewfinder
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout, QGridLayout, QGroupBox, QScrollArea, \
QPushButton, QSizePolicy
from win32comext.shell import shell, shellcon
class Main(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(300, 300)
self.setWindowTitle('Test')
self.available_cameras = QCameraInfo.availableCameras()
self.viewfinder = QCameraViewfinder()
self.viewfinder.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
grid = QGridLayout()
grid.setObjectName('main_gridlayout')
grid.addWidget(self.update_photo_btn(), 0, 0, Qt.AlignCenter)
grid.addWidget(self.viewfinder, 1, 0, Qt.AlignCenter)
grid.addWidget(self.showImg(), 2, 0, Qt.AlignCenter)
self.setLayout(grid)
self.select_camera()
def update_photo_btn(self):
but = QPushButton('Сделать фото и Обновить')
but.setFixedSize(200, 50)
but.clicked.connect(self.thread)
return but
def thread(self):
task_1 = threading.Thread(target=self.func_click_photo)
task_1.start()
task_1.join()
task_2 = threading.Thread(target=self.func_updater())
task_2.start()
task_2.join()
def func_click_photo(self):
millitime = round(time.time() * 1000)
timestamp = time.strftime(f"%d%m%Y-{millitime}")
self.capture.capture(os.path.join(f"test-{timestamp}.jpg"))
def func_updater(self):
grid = self.findChild(QGridLayout, 'main_gridlayout')
box = self.findChild(QGroupBox, 'main_groupbox')
if grid is None:
print('Некуда вставить новый QGroupBox!')
elif box is None:
grid.addWidget(self.showImg(), 2, 0, Qt.AlignCenter)
else:
grid.removeWidget(box)
box.deleteLater()
grid.addWidget(self.showImg(), 2, 0, Qt.AlignCenter)
def select_camera(self):
self.camera = QCamera(self.available_cameras[0])
self.camera.setViewfinder(self.viewfinder)
self.camera.setCaptureMode(QCamera.CaptureStillImage)
self.camera.start()
supported_formats = QCamera.supportedViewfinderResolutions(self.camera)
height_cam = int(supported_formats[0].width())
width_cam = int(supported_formats[0].height())
self.setting = QCameraViewfinderSettings()
self.setting.setResolution(height_cam, width_cam)
self.camera.setViewfinderSettings(self.setting)
self.capture = QCameraImageCapture(self.camera)
def find(self, pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
def showImg(self):
path = shell.SHGetKnownFolderPath(shellcon.FOLDERID_Pictures)
all_image = self.find('*.jpg', f'{path}')
pix_dict = []
for image in all_image:
pxm = QPixmap(image)
pix_dict.append(pxm)
box = QGroupBox()
box.setObjectName('main_groupbox')
box.setStyleSheet("border:0;")
scr = QScrollArea(self)
pnl = QWidget(self)
vbox = QVBoxLayout()
for image in list(reversed(pix_dict)):
photo_label = QLabel()
photo_label.setAlignment(Qt.AlignCenter)
photo_label.setMaximumSize(200, 120)
photo_label.setPixmap(image.scaled(
photo_label.width(), photo_label.height(), Qt.KeepAspectRatio))
vbox.addWidget(photo_label)
pnl.setLayout(vbox)
scr.setWidget(pnl)
scr.setWidgetResizable(True)
group_box_layout = QVBoxLayout()
group_box_layout.addWidget(scr)
box.setLayout(group_box_layout)
return box
if __name__ == "__main__":
App = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(App.exec_())
我遇到了一个问题,我无法更新QGroupBox
.
我想从Windows 中的标准图片文件夹接收所有图片,然后单击按钮,如果图片较多或较少,请在 中更新view
,但启动时,updater
该函数showImg
会收到一个包含新图像的列表并将它们放入在列表内pix_dict
,但不重绘小部件。
这是 PyQT5 中可重现的最小示例:
import fnmatch
import os
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout, QGridLayout, QGroupBox, QScrollArea, QPushButton
from win32comext.shell import shell, shellcon
class Main(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(300, 300)
self.setWindowTitle('Test')
grid = QGridLayout()
grid.addWidget(self.update_photo(), 0, 0, Qt.AlignCenter)
grid.addWidget(self.showImg(), 1, 0, Qt.AlignCenter)
grid.addWidget(self.test_widget_2(), 2, 0, Qt.AlignCenter)
self.setLayout(grid)
def update_photo(self):
but = QPushButton('Обновить')
but.setFixedSize(200, 50)
but.clicked.connect(self.updater)
return but
def test_widget_2(self):
but = QPushButton('test_but_2')
but.setFixedSize(200, 50)
return but
def updater(self):
self.showImg().close()
self.showImg()
def find(self, pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
def showImg(self):
path = shell.SHGetKnownFolderPath(shellcon.FOLDERID_Pictures)
all_image = self.find('*.jpg', f'{path}')
pix_dict = []
for image in all_image:
pxm = QPixmap(image)
pix_dict.append(pxm)
box = QGroupBox()
box.setStyleSheet("border:0;")
scr = QScrollArea(self)
scr.setStyleSheet('height:0px; width:0px;')
pnl = QWidget(self)
vbox = QVBoxLayout(self)
for image in list(reversed(pix_dict)):
photo_label = QLabel()
photo_label.setAlignment(Qt.AlignCenter)
photo_label.setMaximumSize(200, 120)
photo_label.setPixmap(image.scaled(photo_label.width(), photo_label.height(), Qt.KeepAspectRatio))
vbox.addWidget(photo_label)
pnl.setLayout(vbox)
scr.setWidget(pnl)
scr.setWidgetResizable(True)
group_box_layout = QVBoxLayout()
group_box_layout.addWidget(scr)
box.setLayout(group_box_layout)
return box
if __name__ == "__main__":
App = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(App.exec())
动态创建按钮的问题。我正在写一个应用程序,我需要:
现在是什么:
如果有人有任何想法,我将不胜感激。我附上了一个最小的工作示例。
main.py 文件:
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QGroupBox, QPushButton, QMessageBox, QMenu
from PyQt5.QtCore import QEvent, QSettings, Qt
from PyQt5.QtGui import QIcon
class Main(QWidget):
settings = QSettings("settings.ini", QSettings.IniFormat)
def __init__(self):
super(Main, self).__init__()
self.setWindowTitle('Образец')
self.resize(500, 300)
grid = QGridLayout()
grid.addWidget(self.prog_group_box(), 0, 0, 1, 1)
grid.addWidget(self.b_new_prog(), 1, 0, Qt.AlignRight)
self.setLayout(grid)
def prog_group_box(self):
groupBox1 = QGroupBox(self)
self.grid_prog = QGridLayout()
groupBox1.setLayout(self.grid_prog)
return groupBox1
def saved_conf(self):
# Сохранение созданной кнопки в ini файл
self.settings.setValue('button', self.new_but)
self.settings.setValue('label', self.click_newprog._leProgLabel.text())
self.settings.setValue('source', self.click_newprog._leReview.text())
self.settings.sync()
# def restore_settings(self):
# Функция восстановления сохраненного конфига из ini файла
# test = self.settings.setValue('button')
# print(f'RESTORE: {test}')
def delete_setting(self):
# Функция удаления данных из ini файла с сохраненной конфигурацией
self.settings = QSettings("settings.ini", QSettings.IniFormat)
self.settings.remove('button')
def b_new_prog(self):
self.b_new_prog = QPushButton(self)
self.b_new_prog.setText("Добавить")
self.b_new_prog.setMinimumSize(129, 43)
self.b_new_prog.clicked.connect(self.click_newprog)
return self.b_new_prog
def click_newprog(self):
from second import Second
self.click_newprog = Second(self)
self.click_newprog.show()
def create_new_button(self):
self.new_but = QPushButton()
self.new_but.setFixedSize(70, 70)
self.new_but.clicked.connect(self.btnClicked)
self.new_but.setText(self.click_newprog._leProgLabel.text())
self.grid_prog.addWidget(self.new_but, 0, 0)
i = self.grid_prog.count() - 1
self.grid_prog.addWidget(self.new_but, 1 + i // 8, i % 8)
self.new_but.installEventFilter(self)
def btnClicked(self):
import os
os.startfile(self.click_newprog._leReview.text())
# Контекстное меню
def eventFilter(self, source, event):
if event.type() == QEvent.ContextMenu and source is self.new_but:
menu = QMenu()
menu.addAction('Удалить')
if menu.exec_(event.globalPos()):
reply = QMessageBox.question(
self,
'Message', "Вы действительно хотите удалить?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
self.new_but.hide()
self.delete_setting()
else:
pass
return super().eventFilter(source, event)
if __name__ == ('__main__'):
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
第二个.py 文件:
from PyQt5.QtWidgets import (QLabel, QVBoxLayout, QLineEdit, QPushButton,
QHBoxLayout, QFileDialog, QMessageBox, QDialog)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
class Second(QDialog):
def __init__(self, Main):
super().__init__()
self.main = Main
self.setMinimumSize(300, 160)
self.setWindowFlags(Qt.Dialog)
vbox = QVBoxLayout()
hbox = QHBoxLayout()
hbox.addWidget(self._lProgLabel())
hbox.addWidget(self._leProgLabel())
vbox.addLayout(hbox)
vbox.addWidget(self._lReview())
hbox2 = QHBoxLayout()
hbox2.addWidget(self._leReview())
hbox2.addWidget(self._bReview())
vbox.addLayout(hbox2)
hbox3 = QHBoxLayout()
hbox3.addWidget(self.b_create())
hbox3.addWidget(self.b_close())
vbox.addLayout(hbox3)
self.setLayout(vbox)
def _lProgLabel(self):
_lProgLabel = QLabel(self)
_lProgLabel.setText('<center style=font-size:10pt><FONT FACE="Century Gothic">Название кнопки:</center>')
return _lProgLabel
def _leProgLabel(self):
self._leProgLabel = QLineEdit(self)
self._leProgLabel.setFont(QFont('Century Gothic', 10))
return self._leProgLabel
def _lReview(self):
_lreview = QLabel(self)
_lreview.setText(
'<center style=font-size:10pt><FONT FACE="Century Gothic">Укажите путь к программе или нажмите "Обзор":</center>')
return _lreview
def _leReview(self):
self._leReview = QLineEdit(self)
self._leReview.setFixedSize(250, 30)
self._leReview.setFont(QFont('Century Gothic', 10))
return self._leReview
def _bReview(self):
_breview = QPushButton()
_breview.setFixedSize(90, 30)
_breview.setText("Обзор")
_breview.clicked.connect(self.browseFiles)
return _breview
def browseFiles(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', 'C:\Program Files', 'exe files (*.exe)')
self._leReview.setText(fname[0])
def b_create(self):
b_create = QPushButton(self)
b_create.setText("Добавить")
b_create.setMinimumSize(10, 40)
b_create.clicked.connect(self.create_button)
return b_create
def b_close(self):
b_close = QPushButton(self)
b_close.setText("Отмена")
b_close.setMinimumSize(10, 40)
b_close.clicked.connect(self._cancel)
return b_close
def _cancel(self):
self.close()
def showMessageBox(self, title, message):
msgBox = QMessageBox()
msgBox.setWindowTitle(title)
msgBox.setText(message)
msgBox.setStyleSheet("font: 12px;"
"font-family: Century Gothic;")
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec_()
# Проверка ввода данных
def create_button(self):
if len(self._leReview.text()) == 0:
self.showMessageBox('Внимание!',
'<center><br/><u style=font-size:10pt><FONT FACE="Arial"><b>Вы не заполнили поля</b></u></center></FONT>')
else:
self.main.create_new_button()
self.main.saved_conf()
self.close()
if __name__ == ('__main__'):
w = Second()
w.show()