单击按钮时加载其他窗口.PyQt [英] Load other windows when button clicked. PyQt
问题描述
我正在尝试使用 PyQt4 从 python 2.7 中的按钮单击调用另一个窗口.下面的代码打开 AddBooking 对话框,但立即关闭它.我是 Gui 编程的新手,有人能告诉我我的代码有什么问题吗?
I am trying to call another window from a button click in python 2.7 using PyQt4. The code below opens the AddBooking dialog but immediately closes it. Im new to Gui programming, can somebody please tell me what is wrong with my code?
from PyQt4 import QtGui
from HomeScreen import Ui_HomeScreen
from AddBooking import Ui_AddBooking
import sys
class HomeScreen(QtGui.QWidget, Ui_HomeScreen):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.show()
self.Add_Booking_Button.clicked.connect(self.handleButton)
def handleButton(self):
AddBooking2()
class AddBooking2(QtGui.QWidget, Ui_AddBooking):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = HomeScreen()
window.show()
sys.exit(app.exec_())
推荐答案
对话框会立即关闭,因为您没有保留对它的引用,因此一旦超出范围,它就会被垃圾收集.
The dialog closes immediately because you are not keeping a reference to it, and so it will get garbage-collected as soon as it goes out of scope.
>
修复它的最简单方法是执行以下操作:
The simplest way to fix it would be to do something like this:
def handleButton(self):
self.dialog = AddBooking2()
self.dialog.show()
并且您还可以从 AddBooking2.__init__
和 HomeScreen.__init__
中删除 self.show()
行,它们是多余的.除此之外,您的代码看起来不错.
and you can also remove the self.show()
lines from AddBooking2.__init__
and HomeScreen.__init__
, which are redundant. Other than that, your code looks fine.
这篇关于单击按钮时加载其他窗口.PyQt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!