gpt4 book ai didi

python-3.x - PyQt用键盘按钮改变图片

转载 作者:行者123 更新时间:2023-12-05 04:09:12 25 4
gpt4 key购买 nike

这是我在这里的第一篇文章,我还没有在任何地方看到它,所以希望它没问题。我正在尝试通过单击键盘来更改显示的图像(想想幻灯片)。到目前为止,这是我的代码:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import os

class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Document Analysis'
self.left = 30
self.top = 30
self.width = 640
self.height = 480
self.imagenumber=0
self.initUI()

def keyPressEvent(self, event):
key=event.key()
if key==Qt.Key_Right:
self.imagenumber=self.imagenumber+1
self.showimage(self.imagenumber)
self.show()
else:
super(self).keyPressEvent(event)

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.showimage(0)
self.show()

def showimage(self,imagenumber):
label = QLabel(self)
directory = "C:\\Desktop\\Pictures"
imagelist = os.listdir(directory)
pixmap = QPixmap(directory + '\\' + imagelist[imagenumber])
label.setPixmap(pixmap)
self.resize(pixmap.width() + 500, pixmap.height())
self.show()



if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

它似乎有点进展,第一个图像显示得很好,而且我知道 imagenumber 确实发生了变化,当我一开始阻止它显示时,它调整了窗口大小但仍然没有显示图像。对我做错了什么有什么建议吗?

这是一个更大项目的一部分,这就是图片侧面有额外空间的原因,但我们将不胜感激。

最佳答案

你很接近。尝试以下...

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import os

class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Document Analysis'
self.left = 30
self.top = 30
self.width = 640
self.height = 480
self.imagenumber=0
self.initUI()

def keyPressEvent(self, event):
key=event.key()
if key==Qt.Key_Right:
self.imagenumber=self.imagenumber+1
self.showimage(self.imagenumber)
# self.show()
else:
super(self).keyPressEvent(event)

def initUI(self):
layout = QVBoxLayout()
self.setLayout(layout)
self.label = QLabel(self)
layout.addWidget(self.label)

self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.showimage(0)
self.show()

def showimage(self,imagenumber):
# label = QLabel(self)

directory = "C:\\Desktop\\Pictures"
imagelist = os.listdir(directory)
pixmap = QPixmap(directory + '\\' + imagelist[imagenumber])

# label.setPixmap(pixmap)
self.label.setPixmap(pixmap)
self.resize(pixmap.width() + 500, pixmap.height())
# self.show()


if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

主要是,您需要一个持久性标签。您也只需调用 show() 一次。

关于python-3.x - PyQt用键盘按钮改变图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46493125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com