Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 关于PyQt5的问题_Python_Pyqt5 - Fatal编程技术网

Python 关于PyQt5的问题

Python 关于PyQt5的问题,python,pyqt5,Python,Pyqt5,我正在尝试创建一个简单的界面,如下所示: from PyQt5 import QtWidgets,QtGui class program(): def __init__(self): self.window = QtWidgets.QWidget() self.window.setWindowTitle("how many click") self.text = QtWidgets.QLabel(self.window)

我正在尝试创建一个简单的界面,如下所示:

from PyQt5 import QtWidgets,QtGui
class program():

    def __init__(self):

       self.window = QtWidgets.QWidget()
       self.window.setWindowTitle("how many click")

       self.text = QtWidgets.QLabel(self.window)
       self.text.setText(("not clicked"))     
       self.text.setGeometry(240,200,300,50)

       self.text2 = QtWidgets.QLabel(self.window)

       self.picture = QtWidgets.QLabel(self.window)

       self.button=QtWidgets.QPushButton(self.window)
       self.button.setText("click")
       self.button.setFont(QtGui.QFont('',10))
       self.button.setGeometry(250,100,200,50)

       self.window.setGeometry(600,200,800,600)

       self.window.show()

       self.count=0

       self.button.clicked.connect(self.click)

     def click(self):
       self.count+= 1
       self.text.setText(((f"you clicked {self.count} times")))
       self.text.setFont(QtGui.QFont('',10))

       if  self.count == 5:

          self.text2.setText(("You clicked too much"))
          self.text2.setGeometry(250, 250, 300, 50)
          self.picture.setPixmap(QtGui.QPixmap("C:/Users/Administrator/Desktop/mypic.png"))
          self.picture.move(300, 300)

 app = QtWidgets.QApplication(sys.argv)

 run= program()

 sys.exit(app.exec_())
在这段代码中,当我点击5次按钮时,我的图片出现了,但图片变得非常小,如图1所示。然而,当我将setPixmap和picture.move代码写入init函数时,picture会变成正常大小,如pic2所示

pic1:
pic2:

解决问题的简单方法是在设置pixmap后添加以下行:

self.picture.adjustSize()
直接原因是,当显示小部件时,标签还没有一个pixmap,因此其几何体已经设置为其最小大小(默认为100x30)。然后,当设置pixmap时,标签不会自动更新其大小

逻辑上的原因是,您正在为小部件使用固定的几何图形,由于许多原因,通常不鼓励使用这种方法,最重要的是窗口中的元素应始终根据父窗口的大小调整其几何图形(大小和位置),可能是通过占用所有可用空间,并防止窗口大小调整为较小时图元不可见

为了避免这种情况,您应该始终使用(在您的情况下,QVBoxLayout就足够了)

例如:

class program():

    def __init__(self):

        self.window = QtWidgets.QWidget()
        # ...
        layout = QtWidgets.QVBoxLayout(self.window)
        layout.addWidget(self.text)
        layout.addWidget(self.text2)
        layout.addWidget(self.picture)
        layout.addWidget(self.button)

        # it's good practice to always show the window *after* adding all elements
        self.window.show()

非常感谢你的帮助,我会研究你的评论