为PyQt4界面添加点击时打印'Goodbye'的Logout按钮
Got it, let's get your code sorted out and add that logout button you need. Here's the full working version, with all missing pieces filled in and the logout functionality implemented:
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui global username username = " " class Home(QtGui.QWidget): def __init__(self): super(Home, self).__init__() self.initUI() def initUI(self): font = QtGui.QFont("Arial",10,QtGui.QFont.Bold,False) # Username label and input field username_label = QtGui.QLabel('Username', self) username_label.move(10,40) username_label.setFont(font) self.usernameEdit = QtGui.QLineEdit(self) self.usernameEdit.move(100,35) self.usernameEdit.textChanged[str].connect(self.onChangedusername) self.usernameEdit.setFocus() # Finished the cut-off line from your original code # Add Logout button logout_btn = QtGui.QPushButton('Logout', self) logout_btn.move(100, 70) # Positioned below the username input logout_btn.clicked.connect(self.logoutClicked) # Window configuration self.setGeometry(300, 300, 250, 120) self.setWindowTitle('Home Window') self.show() def onChangedusername(self, text): # Update the global username variable when input changes global username username = text print(f"Username updated to: {username}") # Optional feedback def logoutClicked(self): # Action when logout button is clicked print('Goodbye') # Uncomment the line below if you want to close the window on logout # self.close() def main(): # Initialize and run the application app = QtGui.QApplication(sys.argv) ex = Home() sys.exit(app.exec_()) if __name__ == '__main__': main()
Key Changes Made:
- Fixed syntax issues: Split the shebang and encoding declaration into separate lines (your original had them combined, which can cause interpreter errors).
- Completed the username input: Finished the
setFocus()call that was cut off in your code, so the input field gets focus when the window opens. - Added Logout Button: Created a
QPushButtonlabeled "Logout", positioned it below the username field, and connected itsclickedsignal to a custom handler method. - Implemented logout functionality: The
logoutClickedmethod prints 'Goodbye' when the button is pressed. You can uncommentself.close()if you want the window to close after logging out. - Added missing method: Defined
onChangedusernameto handle updates to the username input (your original code referenced this method but didn't define it). - Added application entry point: The
mainfunction initializes the PyQt app and launches the Home window, which was missing in your original snippet.
内容的提问来源于stack exchange,提问作者mahal
相关产品推荐
相关产品推荐

