我有两个.py
个文件,分别是simple_1.py
和simple_2.py
。
单击simple_1.py中的按钮时如何显示simple_2.py的窗口?
同样,当我点击simple_2.py中的按钮时,如何显示simple_1.py的窗口?
当窗口被另一个.py文件调出时,现在这个窗口必须同时关闭
这是我的simple_1.py代码:
# -*- coding: utf-8 -*-
#simple_1.py
import sys
from PyQt4 import QtCore, QtGui
from simple import Ui_Form
class StartQT4(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.button()
def button(self):
button1= QtGui.QPushButton('show simple_2', self)
button1.setGeometry(80, 80,100, 50)
self.connect(button1, QtCore.SIGNAL('clicked()'),
self.buttonClicked)
def buttonClicked(self):
#to show window of simple_2.py
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
这是我的simple_2.py代码:
# -*- coding: utf-8 -*-
#simple_2.py
import sys
from PyQt4 import QtCore, QtGui
class Apple(QtGui.QWidget):
def __init__(self,parent=None):
super().__init__()
self.widget = QtGui.QWidget()
self.resize(250, 150)
self.setWindowTitle('simple2')
self.button()
def button(self):
button1= QtGui.QPushButton('show simple_1', self)
button1.setGeometry(80, 80, 100, 50)
self.connect(button1, QtCore.SIGNAL('clicked()'),
self.buttonClicked)
def buttonClicked(self):
#to show window of simple_1.py
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mywidget = Apple()
mywidget.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
您的代码中有多个错误会阻止您发布的示例运行。我会忽略它们并回答你的实际问题,我可以告诉你的是:
如何让我的两个Qt小部件创建并显示彼此的实例?
首先,我建议将小部件更改为QDialogs
,其中有一个方便的exec_()
方法。您可以通过继承QtGui.QDialog
而非QtGui.QWidget
来执行此操作:
class Apple(QtGui.QDialog):
您需要做的下一件事是在按钮回调中导入并运行自定义QDialog。
def buttonClicked(self):
from simple_1 import StartQT4 # imports your dialog from your other file
sqt = StartQT4() # creates an instance of it
self.close() # closes the current dialog
sqt.exec_() # runs the newly created dialog