提交 2bde067b 编写于 作者: W wizardforcel

2019-11-21 17:31:13

上级 7b775937
# PyQt5 窗口
> 原文: [https://pythonspot.com/pyqt5-window/](https://pythonspot.com/pyqt5-window/)
如果您尚未安装 [PyQT5](https://pythonspot.com/pyqt5/) ,则应先安装。 在终端中,您可以输入:
```
sudo apt-get install python3-pyqt5
```
如果您使用 Windows 或 Mac 计算机,则可以从以下网站下载 [PyQT5](https://pythonspot.com/pyqt5/)[https://www.riverbankcomputing.com/software/pyqt/download5](https://www.riverbankcomputing.com/software/pyqt/download5)
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt5 窗口
You can create a **[PyQT5](https://pythonspot.com/pyqt5/)** window using the code below:
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 simple window - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
我们使用 setGeometry(left,top,width,height)方法设置窗口大小。 使用 setWindowTitle(title)设置窗口标题。 最后调用 show()以显示窗口。
运行:
```
python3 window.py
```
![pyqt5-window](img/4759d47def6e28610123bd8cc0a9a6bf.jpg)
[下载 PyQT5 代码](https://pythonspot.com/download-pyqt5-examples/)
输出看起来应该类似于上面的屏幕截图(取决于您的操作系统)。
\ No newline at end of file
# PyQt5 按钮
> 原文: [https://pythonspot.com/pyqt5-buttons/](https://pythonspot.com/pyqt5-buttons/)
PyQt5 支持使用 QPushButton 类的按钮。 此类在 PyQt5.QtWidgets 组中。 可以通过调用构造函数 QPushButton 并将其文本显示为参数来创建按钮。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**简介** 要将按钮用于 [PyQt5](https://pythonspot.com/pyqt5/) 应用程序,我们需要更新导入行:
```
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
```
在 initUI()方法中,添加以下代码行:
```
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
```
QPushButton 创建小部件,第一个参数是按钮上的文本。 当用户将鼠标指向按钮时,setToolTip 方法显示消息。 最后,将按钮移动到坐标 x = 100,y = 70。 我们需要为按钮单击创建一种方法:
```
@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
```
使用以下命令将连接方法添加到单击:
```
button.clicked.connect(self.on_click)
```
最终 [PyQt5](https://pythonspot.com/pyqt5/) 按钮代码:
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
![pyqt5-button](img/21216682f087b65cf13cc14fe0839117.jpg)
上面的 [PyQt5](https://pythonspot.com/pyqt5/) 按钮示例的屏幕截图。
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 消息框
> 原文: [https://pythonspot.com/pyqt5-messagebox/](https://pythonspot.com/pyqt5-messagebox/)
在本文中,您将学习如何创建 [**PyQt5**](https://pythonspot.com/pyqt5/) 消息框:
![pyqt5-messagebox](img/cf4c779d69c693df5e8c1e309437d6ef.jpg)
为了显示一个消息框,我们需要导入 **QMessageBox**
```
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
```
我们使用方法 **QMessageBox.question()**显示消息框。
**相关课程:** [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**PyQt5 消息框代码** 复制以下代码以显示消息框。
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 messagebox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if buttonReply == QMessageBox.Yes:
print('Yes clicked.')
else:
print('No clicked.')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
**消息框的更多按钮** 考虑到我们使用 **QMessageBox。是****QMessageBox.No** 。 我们可以轻松添加其他选项:
```
buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you want to save?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
print(int(buttonReply))
if buttonReply == QMessageBox.Yes:
print('Yes clicked.')
if buttonReply == QMessageBox.No:
print('No clicked.')
if buttonReply == QMessageBox.Cancel:
print('Cancel')
```
可用的按钮有:
| 总览 | | |
| QMessageBox.Cancel | QMessageBox.Ok | QMessageBox.Help |
| QMessageBox.Open | QMessageBox.Save | QMessageBox.SaveAll |
| QMessageBox.Discard | QMessageBox。关闭 | QMessageBox.Apply |
| QMessageBox.Reset | QMessageBox。是 | QMessageBox.YesToAll |
| QMessageBox.No | QMessageBox.NoToAll | QMessageBox.NoButton |
| QMessageBox.RestoreDefaults | QMessageBox.Abort | QMessageBox.Retry |
| QMessageBox.Ignore |
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 文本框示例
> 原文: [https://pythonspot.com/pyqt5-textbox-example/](https://pythonspot.com/pyqt5-textbox-example/)
在本文中,您将学习如何在 [**PyQt5**](https://pythonspot.com/pyqt5/) 中使用文本框。 该小部件称为 **QLineEdit** ,并具有 **setText** ()来设置文本框值的方法,以及**文本**()来获取值的方法。
我们可以使用 resize(width,height)方法设置文本框的大小。 可以使用 move(x,y)方法或使用网格布局来设置位置。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**PyQt5 文本框** 创建文本框非常简单:
```
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)
```
![pyqt5-QLineEdit](img/4c1c799e1aa4d7f3a9c4b9104ff0efe2.jpg)
**PyQt5 文本框示例**
下面的示例创建一个带有文本框的窗口。
```
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)
# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,80)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)
self.textbox.setText("")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# PyQt5 菜单
> 原文: [https://pythonspot.com/pyqt5-menu/](https://pythonspot.com/pyqt5-menu/)
要为 [**PyQt5**](https://pythonspot.com/pyqt5/) 程序创建菜单,我们需要使用 QMainWindow。 这种类型的菜单在许多应用程序中都可见,并显示在窗口栏的正下方。 它通常具有文件和编辑子菜单。
**相关课程:** [使用 PyQt5 创建 GUI 应用程序](https://gum.co/pysqtsamples)
可以使用 menuBar()方法创建顶部菜单。 子菜单添加了 addMenu(name) 示例:
```
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
editMenu = mainMenu.addMenu('Edit')
viewMenu = mainMenu.addMenu('View')
searchMenu = mainMenu.addMenu('Search')
toolsMenu = mainMenu.addMenu('Tools')
helpMenu = mainMenu.addMenu('Help')
```
可以将单个按钮添加到菜单中,如下所示:
```
exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(self.close)
fileMenu.addAction(exitButton)
```
**PyQt5 菜单示例**
完整代码:
```
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 menu - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 400
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
editMenu = mainMenu.addMenu('Edit')
viewMenu = mainMenu.addMenu('View')
searchMenu = mainMenu.addMenu('Search')
toolsMenu = mainMenu.addMenu('Tools')
helpMenu = mainMenu.addMenu('Help')
exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(self.close)
fileMenu.addAction(exitButton)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
结果: ![pyqt5-menu](img/c5f854a140b5ba105f0ef20d4ef12150.jpg)
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 表
> 原文: [https://pythonspot.com/pyqt5-table/](https://pythonspot.com/pyqt5-table/)
在本文中,您将学习如何将表与 [**PyQt5**](https://pythonspot.com/pyqt5/) 结合使用。 您可以将一个或多个表添加到任何 PyQt 应用程序或窗口。
表可以具有多个行和列。 可以使用 setRowCount()和 setColumnCount()来指定。
![PyQt5 table](img/b1cecef71e11f781248c0be0b90beddd.jpg)
要添加表,您将需要导入 **QTableWidget****QTableWidgetItem**
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## [](#Example "Example")范例
```
from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem
```
使用以下命令创建一个表:
```
self.tableWidget = QTableWidget()
# set row count
self.tableWidget.setRowCount(4)
# set column count
self.tableWidget.setColumnCount(2)
```
要添加单个单元格:
```
self.tableWidget.setItem(X,Y, QTableWidgetItem("TEXT"))
```
**PyQt5 表示例** 完整的 [**PyQt5**](https://pythonspot.com/pyqt5/) 表代码如下:
```
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 table - pythonspot.com'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createTable()
# Add box layout, add table to box layout and add box layout to widget
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.setLayout(self.layout)
# Show widget
self.show()
def createTable(self):
# Create table
self.tableWidget = QTableWidget()
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
self.tableWidget.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
self.tableWidget.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
self.tableWidget.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
self.tableWidget.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
self.tableWidget.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
self.tableWidget.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
self.tableWidget.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
self.tableWidget.setItem(3,1, QTableWidgetItem("Cell (4,2)"))
self.tableWidget.move(0,0)
# table selection change
self.tableWidget.doubleClicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 标签
> 原文: [https://pythonspot.com/pyqt5-tabs/](https://pythonspot.com/pyqt5-tabs/)
在本文中,您将学习将选项卡与 [**PyQt5**](https://pythonspot.com/pyqt5/) 结合使用。 我们将首先显示完整的代码,然后进行解释。 PyQt5 有一个小部件来创建称为 QTabWidget 的选项卡。 QTabWidget 可以包含选项卡(QWidgets),这些选项卡上具有小部件,例如标签,按钮,图像等。
![pyqt5-tabs](img/ca67319c33ab1709f8fd3eafa79c6dfb.jpg)
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**PyQt5 标签示例** 完整 [**PyQt5**](https://pythonspot.com/pyqt5/) 标签示例:
```
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 tabs - pythonspot.com'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
# Add tabs
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("PyQt5 button")
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
@pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
**说明:**
要将表添加到窗口,我们创建一个新类:
```
class MyTableWidget(QWidget)
```
我们通过为标签创建一个 **QTabWidget** 和两个 **QWidgets** 来初始化标签屏幕。
```
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
```
然后,我们将这些选项卡添加到选项卡小部件中:
```
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
```
使用以下命令创建选项卡的内容:
```
self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("PyQt5 button")
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)
```
最后,我们将标签添加到小部件中:
```
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
```
不要忘记将您的自定义标签窗口小部件添加到窗口中:
```
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 水平布局
> 原文: [https://pythonspot.com/pyqt5-horizo​​ntal-layout/](https://pythonspot.com/pyqt5-horizontal-layout/)
窗口可以包含小部件(按钮,文本字段,图像等)。 窗口小部件经常添加到布局中。 水平布局可用于在水平方向上(动态)添加小部件。
在本文中,我们将向您展示如何使用水平布局在水平方向上添加按钮。
![pyqt5-horizontal-layout](img/b18a764c1fce5b869fc970d63229d0d9.jpg)
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**水平布局示例** 我们将显示整个代码,然后进行解释。
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QDialog):
def __init__(self):
super().__init__()
self.title = 'PyQt5 layout - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createHorizontalLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def createHorizontalLayout(self):
self.horizontalGroupBox = QGroupBox("What is your favorite color?")
layout = QHBoxLayout()
buttonBlue = QPushButton('Blue', self)
buttonBlue.clicked.connect(self.on_click)
layout.addWidget(buttonBlue)
buttonRed = QPushButton('Red', self)
buttonRed.clicked.connect(self.on_click)
layout.addWidget(buttonRed)
buttonGreen = QPushButton('Green', self)
buttonGreen.clicked.connect(self.on_click)
layout.addWidget(buttonGreen)
self.horizontalGroupBox.setLayout(layout)
@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
**解释**
我们首先在 initUI()方法中调用 self.createHorizo​​ntalLayout()方法。 在方法内部,我们创建了一个带有标题和水平布局的框:
```
self.horizontalGroupBox = QGroupBox("What is your favorite color?")
layout = QHBoxLayout()
```
我们创建小部件(在此示例中为 QPushButtons),并将它们一个接一个地添加到布局中:
```
buttonBlue = QPushButton('Blue', self)
buttonBlue.clicked.connect(self.on_click)
layout.addWidget(buttonBlue)
```
我们将标题框设置为包含水平布局:
```
self.horizontalGroupBox.setLayout(layout)
```
在 initUI 方法中,我们将其添加到窗口中:
```
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 网格布局
> 原文: [https://pythonspot.com/pyqt5-grid-layout/](https://pythonspot.com/pyqt5-grid-layout/)
[**PyQt5**](https://pythonspot.com/pyqt5/) 支持网格布局,其名称为 **QGridLayout** 。 可以在水平和垂直方向上将小部件添加到网格中。 带有小部件的网格布局示例如下所示:
![pyqt-grid-layout](img/6094d3e9eaea24f4f064dfcd2ea91ddc.jpg)
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**PyQt5 网格布局示例:** 下面的示例创建网格:
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QDialog):
def __init__(self):
super().__init__()
self.title = 'PyQt5 layout - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createGridLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
layout.addWidget(QPushButton('1'),0,0)
layout.addWidget(QPushButton('2'),0,1)
layout.addWidget(QPushButton('3'),0,2)
layout.addWidget(QPushButton('4'),1,0)
layout.addWidget(QPushButton('5'),1,1)
layout.addWidget(QPushButton('6'),1,2)
layout.addWidget(QPushButton('7'),2,0)
layout.addWidget(QPushButton('8'),2,1)
layout.addWidget(QPushButton('9'),2,2)
self.horizontalGroupBox.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
**解释**
我们通过以下方式导入 gridlayout 和其他内容:
```
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
```
在方法 createGridLayout()中,我们创建带有标题的网格并设置大小。
```
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
```
使用添加小部件
```
layout.addWidget(Widget,X,Y)
```
最后,我们设置布局。
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQT5 输入对话框
> 原文: [https://pythonspot.com/pyqt5-input-dialog/](https://pythonspot.com/pyqt5-input-dialog/)
[**PyQt5**](https://pythonspot.com/pyqt5/) 支持多个输入对话框,使用它们可以导入 QInputDialog。
```
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
```
[**PyQt5**](https://pythonspot.com/pyqt5/) 输入对话框概述:
![pyqt5-input-dialog](img/6872d4e6f12488af0c0f4f9c14deb773.jpg)
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**获取整数** 使用 QInputDialog.getInt()获取整数:
```
def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)
```
参数顺序如下:自身,窗口标题,标签(在输入框之前),默认值,最小,最大和步长。
**获得双倍** 通过 QInputDialog.getDouble()获得双倍:
```
def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.05, 0, 100, 10)
if okPressed:
print(d)
```
最后一个参数(10)是逗号后面的小数位数。
**获取项目/选择** 从下拉框中获取一个项目:
```
def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if okPressed and item:
print(item)
```
**获取字符串** 使用 QInputDialog.getText()获取字符串
```
def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)
```
**所有 PyQt5 输入对话框的示例** 下面的完整示例:
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 input dialogs - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.getInteger()
self.getText()
self.getDouble()
self.getChoice()
self.show()
def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)
def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.50, 0, 100, 10)
if okPressed:
print( d)
def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if ok and item:
print(item)
def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 文件对话框
> 原文: [https://pythonspot.com/pyqt5-file-dialog/](https://pythonspot.com/pyqt5-file-dialog/)
[**PyQt5**](https://pythonspot.com/pyqt5/) 支持(本机)文件对话框:打开文件,打开文件和保存文件。 通过调用 PyQt5 中包含的功能,您将获得默认的文件对话框,而无需从头开始重新创建这些对话框。
需要导入 **QFileDialog**
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**文件对话框示例** 使用的方法是 QFileDialog.getOpenFileName(),QFileDialog.getOpenFileNames(),QFileDialog.getSaveFileName()。 使用方法参数可以指定默认目录,文件类型和默认文件名。
![pyqt5-open-file-dialog](img/c145c7271f700e11aa378a211bb94dff.jpg)
下面的代码将显示所有文件对话框:
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 file dialogs - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.openFileNameDialog()
self.openFileNamesDialog()
self.saveFileDialog()
self.show()
def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
if fileName:
print(fileName)
def openFileNamesDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
files, _ = QFileDialog.getOpenFileNames(self,"QFileDialog.getOpenFileNames()", "","All Files (*);;Python Files (*.py)", options=options)
if files:
print(files)
def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options)
if fileName:
print(fileName)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# PyQt5 图片
> 原文: [https://pythonspot.com/pyqt5-image/](https://pythonspot.com/pyqt5-image/)
PyQt5(和 Qt)默认情况下支持图像。 在本文中,我们将向您展示如何向窗口添加图像。 可以使用 QPixmap 类加载图像。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**PyQt5 图像简介** 将图像添加到 [PyQt5](https://pythonspot.com/pyqt5/) 窗口就像创建标签并将图像添加到该标签一样简单。
```
label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)
# Optional, resize window to image size
self.resize(pixmap.width(),pixmap.height())
```
这些是必需的导入:
```
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
```
![pyqt5 qpixmap](img/7c8aa302666166e4fa6969572c501f04.jpg)
**PyQt5 加载图片(QPixmap)**
复制下面的代码并运行。 该映像应与程序位于同一目录中。
```
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 image - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create widget
label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)
self.resize(pixmap.width(),pixmap.height())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)
\ No newline at end of file
# Qt4 窗口
> 原文: [https://pythonspot.com/qt4-window/](https://pythonspot.com/qt4-window/)
![pyqt window](img/1629a04730237a4379bd58ced163e08f.jpg) [PyQt4](https://pythonspot.com/pyqt4/) window on Ubuntu
在本教程中,您将学习如何使用 [PyQT4](https://pythonspot.com/pyqt4/) 创建图形 hello world 应用程序。
[PyQT4](https://pythonspot.com/pyqt4/) ,它是[图形用户界面(GUI)](https://pythonspot.com/gui)编程的 Python 选项之一。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt4 窗口示例:
This application will create a graphical window that can be minimized, maximimzed and resized it.
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("Hello World!")
# Show window
w.show()
sys.exit(a.exec_())
```
必须导入 [PyQT4](https://pythonspot.com/pyqt4/) 模块,我们通过以下代码行进行导入:
```
from PyQt4.QtGui import *
```
我们使用 QApplication()创建 [PyQT4](https://pythonspot.com/pyqt4/) 应用程序对象:
```
a = QApplication(sys.argv)
```
我们创建窗口(QWidget),调整大小,设置标题并显示以下代码:
```
w = QWidget()
w.resize(320, 240)
w.setWindowTitle("Hello World!")
```
不要忘记显示窗口:
```
# Show window
w.show()
```
您可以下载 PyQt4 示例集合: , [下载 PyQT 代码(批量集合)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# Qt4 按钮
> 原文: [https://pythonspot.com/qt4-buttons/](https://pythonspot.com/qt4-buttons/)
![PyQt4 button example](img/3911a344ee61b701979eb5a2de2c4e27.jpg) PyQt4 button example
PyQt4(Qt4)通过 QPushButton 小部件支持按钮。
我们扩展代码以在窗口中心显示一个按钮。
如果将鼠标悬停在该按钮上将显示一个工具提示,按下该按钮将关闭程序。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt4 按钮示例
The example below adds a button to a PyQt4 window.
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("Hello World!")
# Add a button
btn = QPushButton('Hello World!', w)
btn.setToolTip('Click to quit!')
btn.clicked.connect(exit)
btn.resize(btn.sizeHint())
btn.move(100, 80)
# Show window
w.show()
sys.exit(a.exec_())
```
## PyQt4 信号和插槽
A button click should do something. To do so, you must use signals and slots.
如果用户执行诸如单击按钮,在框中键入文本之类的操作,则小部件会发出信号。 信号可以与一个插槽相连,该插槽充当接收器并对其起作用。
```
import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *
# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Button click example @pythonspot.com')
# Create a button in the window
btn = QPushButton('Click me', w)
# Create the actions
@pyqtSlot()
def on_click():
print('clicked')
@pyqtSlot()
def on_press():
print('pressed')
@pyqtSlot()
def on_release():
print('released')
# connect the signals to the slots
btn.clicked.connect(on_click)
btn.pressed.connect(on_press)
btn.released.connect(on_release)
# Show the window and run the app
w.show()
app.exec_()
```
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 消息框
> 原文: [https://pythonspot.com/qt4-messagebox/](https://pythonspot.com/qt4-messagebox/)
[PyQT4](https://pythonspot.com/pyqt4/) 使用多种功能提供消息框功能。 [PyQT4](https://pythonspot.com/pyqt4/) 中包含的 消息框是:问题,警告,错误,信息,批评和关于框。
**相关课程:** [使用 Python PyQt5 创建 GUI 应用程序](https://gum.co/pysqtsamples)
## PyQt4 消息框
The code below will display a message box with two buttons:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')
# Show window
w.show()
sys.exit(a.exec_())
```
结果:
![qtMessagebox question](img/42005bdb1e24d6b5c1b14e5895521e3a.jpg) qtMessagebox question
[PyQT4](https://pythonspot.com/pyqt4/) 提供了不同类型的消息框。
## PyQT4 警告框
You can display a warning box using this line of code:
```
QMessageBox.warning(w, "Message", "Are you sure you want to continue?")
```
## PyQT4 信息框
We can display an information box using QMessageBox.information()
```
QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")
```
结果:
![QMessageBox Info](img/6efbaae64acdb4e69214c7589963b5bd.jpg) QMessageBox Info
## PyQT4 临界盒
If something goes wrong in your application you may want to display an error message.
```
QMessageBox.critical(w, "Message", "No disk space left on device.")
```
Result: ![QMessagebox ](img/af9cd039b8bc48207cfd140b3bd3dd1c.jpg) QMessagebox
## PyQT4 关于盒子
We have shown the question box above.
```
QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")
```
Result: ![qt Messagebox](img/843b3c0a68065ac101f04944c2bac053.jpg) qt Messagebox
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# PyQt4 的菜单
> 原文: [https://pythonspot.com/qt4-menu/](https://pythonspot.com/qt4-menu/)
![PyQT Menu pythonspot](img/08595a6340da7b1792993a5bb8fb5912.jpg) PyQT Menu
[**PyQt4**](https://pythonspot.com/pyqt4/) **菜单**出现在窗口栏的顶部。 **菜单**使用户可以控制应用程序,并且通常位于窗口顶部。
QMainWindow 类创建主应用程序窗口。 此类具有一个名为 menuBar()的方法,该方法添加标题栏。
可以使用 addMenu()将菜单添加到标题栏。 在每个菜单内,您都可以使用 addAction 方法添加命令。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt4 菜单栏
This code will add a menu to your qt4 app:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("Hello World!")
# Create main menu
mainMenu = w.menuBar()
mainMenu.setNativeMenuBar(False)
fileMenu = mainMenu.addMenu('&File')
# Add exit button
exitButton = QAction(QIcon('exit24.png'), 'Exit', w)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(w.close)
fileMenu.addAction(exitButton)
# Show window
w.show()
sys.exit(a.exec_())
```
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 小部件
> 原文: [https://pythonspot.com/qt4-widgets/](https://pythonspot.com/qt4-widgets/)
我们有许多可通过 [PyQT](https://pythonspot.com/pyqt4/) 访问的小部件。 其中包括:
* 文本框
* 组合框
* 日历
For more widgets we suggest using the GUI creation tool covered in the next tutorial.
**相关课程:** [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**文本框小部件** 几乎每个应用程序中都存在输入字段。 在 [PyQT4](https://pythonspot.com/pyqt4/) 中,可以使用 QLineEdit()函数创建输入字段。
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()
# Set window size.
w.resize(320, 100)
# Set window title
w.setWindowTitle("PyQT Python Widget!")
# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)
# Show window
w.show()
sys.exit(a.exec_())
```
![qt textbox](img/8e1ee291a6d4a348a3629298a80fefbd.jpg) qt textbox
**组合框** 组合框可用于从列表中选择一个项目。
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()
# Set window size.
w.resize(320, 100)
# Set window title
w.setWindowTitle("PyQT Python Widget!")
# Create combobox
combo = QComboBox(w)
combo.addItem("Python")
combo.addItem("Perl")
combo.addItem("Java")
combo.addItem("C++")
combo.move(20,20)
# Show window
w.show()
sys.exit(a.exec_())
```
![qt combobox](img/cb9724ae989ef2c079731874772a1798.jpg) qt combobox
**日历小部件** PyQT4 库有一个日历小部件,您可以使用 QCalendarWidget()调用来创建它。
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("PyQT Python Widget!")
# Create calendar
cal = QCalendarWidget(w)
cal.setGridVisible(True)
cal.move(0, 0)
cal.resize(320,240)
# Show window
w.show()
sys.exit(a.exec_())
```
结果:
![calendar qt](img/ab786df4859e36d6feeabac1f97dc5f2.jpg) calendar qt
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# PyQt4 文本框
> 原文: [https://pythonspot.com/qt4-textbox-example/](https://pythonspot.com/qt4-textbox-example/)
![pyqt textbox](img/b2c2549d84491412df87f80cf61fbbdc.jpg) PyQt4 textbox example
在本文中,您将学习如何使用 [PyQt4](https://pythonspot.com/pyqt4/) 与文本框进行交互。
如果要在文本框(QLineEdit)中显示文本,则可以使用 setText()方法。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt4 QLineEdit
The textbox example below changes the text if the button is pressed.
```
import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *
# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Textbox example @pythonspot.com')
# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)
# Set window size.
w.resize(320, 150)
# Create a button in the window
button = QPushButton('Click me', w)
button.move(20,80)
# Create the actions
@pyqtSlot()
def on_click():
textbox.setText("Button clicked.")
# connect the signals to the slots
button.clicked.connect(on_click)
# Show the window and run the app
w.show()
app.exec_()
```
使用以下行创建文本字段:
```
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)
```
该按钮(来自屏幕截图)由以下部分制成:
```
button = QPushButton('Click me', w)
```
我们通过以下方式将按钮连接到 on_click 函数:
```
# connect the signals to the slots
button.clicked.connect(on_click)
```
此函数使用 setText()设置文本框。
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 表
> 原文: [https://pythonspot.com/qt4-table/](https://pythonspot.com/qt4-table/)
我们可以使用 QTableWidget 来显示表格,QTableWidget 是 [PyQt](https://pythonspot.com/pyqt4/) 模块的一部分。 我们设置标题,行数,列数并添加数据。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## Qt4 表示例
An example below:
```
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()
# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)
# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))
# show table
table.show()
return app.exec_()
if __name__ == '__main__':
main()
```
结果:
![PyQT Table](img/185c656e13f47debbad67f5133a4215d.jpg) ![PyQT Table ](img/a60b759f387958b2b4c7046ecd6f4b87.jpg) ![PyQT Table tooltips](img/f1f56d1db3e8574fad782a6392cbb56c.jpg) [PyQT](https://pythonspot.com/pyqt4/) Table tooltips
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 标签
> 原文: [https://pythonspot.com/qt4-tabs/](https://pythonspot.com/qt4-tabs/)
选项卡在图形应用程序中非常有用。 它们出现在网络浏览器,文本编辑器和任何其他应用中。 要创建选项卡式窗口,您需要调用 QTabWidget()函数。 每个选项卡都是您之前看到的 QWidget()。 您可以使用以下功能将 QWidget 与 QTabWidget 连接:
```
tabs.addTab(tab1,"Tab 1")
```
其中第一个参数是选项卡对象,第二个参数是显示在屏幕上的名称。 我们在第一个标签(QWidget)中添加了一些按钮。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**示例代码:**
```
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
def main():
app = QtGui.QApplication(sys.argv)
tabs = QtGui.QTabWidget()
# Create tabs
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()
# Resize width and height
tabs.resize(250, 150)
# Set layout of first tab
vBoxlayout = QtGui.QVBoxLayout()
pushButton1 = QtGui.QPushButton("Start")
pushButton2 = QtGui.QPushButton("Settings")
pushButton3 = QtGui.QPushButton("Stop")
vBoxlayout.addWidget(pushButton1)
vBoxlayout.addWidget(pushButton2)
vBoxlayout.addWidget(pushButton3)
tab1.setLayout(vBoxlayout)
# Add tabs
tabs.addTab(tab1,"Tab 1")
tabs.addTab(tab2,"Tab 2")
tabs.addTab(tab3,"Tab 3")
tabs.addTab(tab4,"Tab 4")
# Set title and show
tabs.setWindowTitle('PyQt QTabWidget @ pythonspot.com')
tabs.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
```
结果:
![PyQT Tabs](img/71481f97c660d6556a1bf3c5b70648bc.jpg) PyQT Tabs
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 进度栏
> 原文: [https://pythonspot.com/qt4-progressbar/](https://pythonspot.com/qt4-progressbar/)
在本文中,我们将演示如何使用 progressbar 小部件。 进度栏与其他小部件的不同之处在于,它会及时更新。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**QT4 进度栏示例** 让我们从代码开始:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT
class QProgBar(QProgressBar):
value = 0
@pyqtSlot()
def increaseValue(progressBar):
progressBar.setValue(progressBar.value)
progressBar.value = progressBar.value+1
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("PyQT4 Progressbar @ pythonspot.com ")
# Create progressBar.
bar = QProgBar(w)
bar.resize(320,50)
bar.setValue(0)
bar.move(0,20)
# create timer for progressBar
timer = QTimer()
bar.connect(timer,SIGNAL("timeout()"),bar,SLOT("increaseValue()"))
timer.start(400)
# Show window
w.show()
sys.exit(a.exec_())
```
实例栏(QProgBar 类的)用于保存进度栏的值。 我们调用函数 setValue()来更新其值。 给定参数 w 将其附加到主窗口。 然后,将其移动到屏幕上的位置(0,20),并为其指定宽度和高度。
为了及时更新进度条,我们需要一个 QTimer()。 我们将小部件与计时器连接起来,计时器将调用函数 gainValue()。 我们将计时器设置为每 400 毫秒重复一次函数调用。 您还会看到单词 SLOT 和 SIGNAL。 如果用户执行诸如单击按钮,在框中键入文本之类的操作,则该小部件会发出信号。 该信号没有任何作用,但可用于连接一个插槽,该插槽充当接收器并对其起作用。
结果:
![PyQT Progressbar](img/72b521dd094d336233ce321ce73811a2.jpg) PyQT Progressbar
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# QT4 像素图(图片)
> 原文: [https://pythonspot.com/qt4-pixmaps-images/](https://pythonspot.com/qt4-pixmaps-images/)
在本文中,我们将演示如何在 [PyQT](https://pythonspot.com/pyqt4/) 窗口中加载和显示图像。 我们可以使用 Pixmap 小部件在 [PyQT](https://pythonspot.com/pyqt4/) 窗口中显示图像。
![PyQt4-load-image](img/77d7b4598127e8b587d29da009865dde.jpg) An image loaded in a PyQt4 window.
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## 介绍
The constructor of Pixmap takes the image path as parameter:
```
pixmap = QPixmap(os.getcwd() + '/logo.png')
```
该映像必须与程序位于同一目录中。 QPixmap 小部件支持 png 和 jpeg。 下面的示例代码。
## PyQT 在 Pixmap 中加载图像
We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.
```
import os
import sys
from PyQt4.QtGui import *
# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")
# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())
# Draw window
w.show()
app.exec_()
```
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
结果:
![pyqt Pixmap](img/02ad7ee98094c1504dca8004682214e4.jpg) pyqt Pixmap
\ No newline at end of file
# QT4 文件对话框
> 原文: [https://pythonspot.com/qt4-file-dialog/](https://pythonspot.com/qt4-file-dialog/)
在这个简短的教程中,您将学习如何创建文件对话框并加载其文件内容。 使用文件访问的许多应用程序都需要文件对话框。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
**文件对话框示例** 要在 [PyQT](https://pythonspot.com/pyqt4/) 中获取文件名(而非文件数据),可以使用以下行:
```
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
```
如果您使用的是 Microsoft Windows,请使用
```
filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')
```
下面的示例(包括加载文件数据):
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("Hello World!")
# Get filename using QFileDialog
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
print(filename)
# print file contents
with open(filename, 'r') as f:
print(f.read())
# Show window
w.show()
sys.exit(a.exec_())
```
结果(输出可能因您的操作系统而异):
![pyqt_file_open](img/a6f06b37951c44452f79efd047298429.jpg) PyQt File Open Dialog.
[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)
\ No newline at end of file
# PyQt4 GUI 教程
> 原文: [https://pythonspot.com/building-an-application-gui-with-pyqt-beginners-tutorial/](https://pythonspot.com/building-an-application-gui-with-pyqt-beginners-tutorial/)
在本教程中,我们将教您如何使用 [PyQT4](https://pythonspot.com/pyqt4/) 创建图形应用程序。 这可以在支持 [PyQT4](https://pythonspot.com/pyqt4/) 的任何平台上使用,包括 Windows,Linux,UNIX,Android,OS X 和 iOS。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## PyQt4 安装
PyQt does not include Qt itself – you may have to obtain it separately. The homepage for PyQt is [https://www.riverbankcomputing.com/software/pyqt/](https://www.riverbankcomputing.com/software/pyqt/).
您将需要安装一些软件包:
```
sudo pip install pyqt
sudo apt-get install qt4-designer
sudo apt-get install pyqt4-dev-tools
sudo apt-get install python-kde4
```
如果找不到 python-kde4,请更新您的存储库以找到它。 如果您使用的是 Ubuntu,请使用此链接。
## 构建一个 PyQT4 GUI
Now we can use the QT Designer application. It saves us from writing tons of layout code that you may be used to when writing HTML. Start qt4-designer from your applications menu. The QT Designer application will appear.![QT_Designer](img/c270198655afac039b29c13193a5885a.jpg) QT Designer
按不带按钮的对话框,然后按创建。 现在,您可以将任何组件从窗口小部件框拖动到表单。 简单的拖放。 我们添加了一个按钮,标签和一个像素图。 (我从网上拍摄了一张随机图作为像素图)
![QT_KDE_Dialog](img/a49e87363988856b8eabf42c30cf9400.jpg) QT KDE Dialog
我们的窗口如上图所示。 按 Form > Viewcode。 我们将在 C ++中得到一个带有表单代码的弹出框! 很好,但是我们需要 Python 代码。 按文件>另存为>form.ui。
文件 test.ui 包含以 XML 格式描述的表单。 (您可以在文本编辑器中查看它)打开控制台并键入:
```
pyuic4 form.ui > form.py
```
运行文件没有任何作用。 创建一个名为 gui.py 的新文件
粘贴以下代码:
```
import sys
from PyQt4 import QtCore, QtGui
from form import Ui_Dialog
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyDialog()
myapp.show()
sys.exit(app.exec_())
```
运行:
```
python gui.py
```
这将打开我们的图形界面。 按下“确定”按钮将仅关闭该应用程序。
![pyqt_window-300x215](img/2b327b721889fb95be65443c1d531d0f.jpg) [PyQt](https://pythonspot.com/pyqt4/) Window with QButton
我们想在按下 OK 按钮时添加一些动作。 我们将以下三行添加到代码中:
```
self.ui.pushButton.clicked.connect(self.OK)
def OK(self):
print 'OK pressed.'
```
![pyqt4 app example](img/e58b77134f9f1ef5de60f6715f4181ef.jpg) [pyqt4](https://pythonspot.com/pyqt4/) app example
[下载 PyQT4 示例(批量收集)](https://pythonspot.com/python-qt-examples/)
您可能会喜欢:[使用 PyQT4](https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/)[创建 Web 浏览器 PyQt4 概述](https://pythonspot.com/pyqt4/)
\ No newline at end of file
# QML 和 PyQT:创建 GUI(教程)
> 原文: [https://pythonspot.com/qml-and-pyqt-creating-a-gui-tutorial/](https://pythonspot.com/qml-and-pyqt-creating-a-gui-tutorial/)
如果您尚未完成我们的[第一个 PyQT 教程](https://pythonspot.com/building-an-application-gui-with-pyqt-beginners-tutorial/),则应该这样做,这很有趣! 在本教程中,我们将使用 [PyQT4](https://pythonspot.com/pyqt4/) 和用户界面标记语言,该语言描述图形用户界面和控件。
**相关课程:**
* [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)
## QML 和 PyQT
An excerpt of user interface markup [graphical user interfaces](https://pythonspot.com/gui/) and language code could look like:
```
Rectangle {
id: simplebutton
color: "grey"
width: 150; height: 75
```
本质上,该语言告诉界面应该是什么样。 我们将使用的语言称为 QML。
## QTCreator
Start a programmed called QTCreator.   The tutorial will be quite graphical to help you through the whole process. Simply type qtcreator in the terminal or start it from the menu list.  This screen should pop up:![qtcreator](img/472f18a048e7f08feb788266c341bfd8.jpg) qtcreator
## 创建一个 GUI
Press the big **New Project** button. Select **QT Quick Application** from the menu below. Finally press **Choose** on the bottom right. ![qtquick](img/a24879ba48cc2b7501b7b33c35f7dc27.jpg) qtquick
将会出现一个新的弹出窗口:
![kde create](img/941e20c7d0c048025948f404e3fb4668.jpg) kde create
输入名称和有效路径以保存您的项目。 然后按下一步。 从菜单列表中选择 **QT Quick 2.0** 。 按下一步。 按完成。 立即出现以 QML 语言定义的用户界面。
![qt quick](img/4d9da0a2b8e81110fd8f9c625e578502.jpg) qt quick
像所有伟大的程序员一样,我们将以最懒惰的方式解决问题。 无需手动输入所有 QML 代码,我们将按下屏幕左侧的**设计**按钮。 现在将出现一个拖放屏幕。
![draganddrop](img/e22af26e044860eabf29f3813b1dfa8b.jpg) draganddrop
我们将图像拖到该区域上,然后选择右侧的源。 保存项目。 打开终端并找到您刚创建的 qml 文件。 或者,您可以简单地将代码复制到编辑框中,然后将其保存到.qml 文件中。 输入命令:
```
qmlviewer main.qml
```
这将显示 qml 文件中定义的窗口,没有任何功能。 它只是界面的查看器。 然后,我们创建一些代码来加载此 QML 定义:
```
import sys
from PyQt4.QtCore import QDateTime, QObject, QUrl, pyqtSignal
from PyQt4.QtGui import QApplication
from PyQt4.QtDeclarative import QDeclarativeView
app = QApplication(sys.argv)
# Create the QML user interface.
view = QDeclarativeView()
view.setSource(QUrl('main.qml'))
view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.setGeometry(100, 100, 400, 240)
view.show()
app.exec_()
```
最后,我们将第一行 main.qml 修改为:
```
import Qt 4.7
```
仅仅是因为我们的 QtQuick 不见了。 跑步
```
python run.py
```
现在将显示 QML 定义的用户界面:
![QML_PyQT](img/f8cf080d83de7cdd12b501d273967d21.jpg) QML and PyQT
所有代码都是 [PyQT](https://pythonspot.com/pyqt4/) ,因此您可以像上一教程中那样添加代码。 这是使用 PyQT 创建图形界面的两种方法。 与在上一教程中使用 [QT](https://pythonspot.com/pyqt4/) 创建 GUI 的方法相比,该方法可能更宽松地与代码耦合。 尽管两者都是有效的方法。
[下载 PyQT4 示例(批量收集)](https://pythonspot.com/python-qt-examples/)
您可能会喜欢:[具有 PyQT4](https://pythonspot.com/building-an-application-gui-with-pyqt-beginners-tutorial/)[PyQt4 教程](https://pythonspot.com/pyqt4/)的应用程序 GUI
\ No newline at end of file
# Tk 窗口和按钮
> 原文: [https://pythonspot.com/tk-window-and-button/](https://pythonspot.com/tk-window-and-button/)
带有 onClick 事件的 **Tk 按钮** 要创建带有按钮的 [**Tkinter**](https://pythonspot.com/tkinter/) 窗口,请使用以下示例。 程序进入 mainloop(),等待事件(用户操作)。 我们定义具有回调函数 callback()的按钮。 master 是根窗口,您的按钮将出现在该窗口中。
```
from Tkinter import *
master = Tk()
def callback():
print "click!"
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()
```
![tk button](img/b1fb57a653c6741ced779c294ca87447.jpg) tk button
**相关课程**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
**Tk 图像按钮** 如果需要图像按钮,请使用 PhotoImage 类。 我们使用函数 minsize()和 geometry()设置窗口的大小和最小大小。 例:
```
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, command=callback, height=50, width=150)
b.pack()
mainloop()
```
结果:
![tk image button](img/289712f8426bbfc6ceacdd22bbcff819.jpg) tk image button
**带有文本标签的[Tk Image]按钮** 如果需要图像和文本,只需添加参数 compound = LEFT。
```
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.pack()
mainloop()
```
结果:
![tk button with text and image](img/966f97e15792c89ebeb6f5f8942b0ee5.jpg) tk button with text and image
**按钮位置** 如果要将按钮放置在坐标上,请不要使用 pack()函数,而要使用 place(x,y)函数,如下例所示:
```
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.place(x = 20, y = 20)
mainloop()
```
结果:
![tk button location](img/f8756b4a6882e933bfd6fc3f8f1fe1b6.jpg) tk 按钮位置 [下载 tkinter 示例](/download-tkinter-examples)
\ No newline at end of file
# Tk 菜单栏
> 原文: [https://pythonspot.com/tk-menubar/](https://pythonspot.com/tk-menubar/)
Tkinter 工具箱包含所有用于创建图形应用程序的基本小部件。 几乎每个应用程序都有一个主菜单。 与预期的一样,Tkinter 支持将主菜单添加到您的应用程序窗口。
下面的屏幕截图演示了基于 Tkinter 的菜单:
![tk menu](img/ec69b97f82c9ef2d0bac39c941f21ed9.jpg) Tkinter menu
**相关课程**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
## Tkinter 菜单栏
You can create a simle menu with [Tkinter](https://pythonspot.com/tkinter/) using the code below. Every option (new, open, save.. ) should have its own callback.
```
from Tkinter import *
def donothing():
x = 0
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
root.mainloop()
```
我们通过调用创建菜单栏:
```
menubar = Menu(root)
```
其中 root 是 Tk()对象。
菜单栏可能包含零个或多个子菜单,例如文件菜单,编辑菜单,视图菜单,工具菜单等。
可以使用相同的 Menu()调用创建子菜单,其中第一个参数是要附加到的菜单栏。
```
filemenu = Menu(menubar, tearoff=0)
menu = Menu(menubar, tearoff=0)
```
可以使用 add_command()方法将各个选项添加到这些子菜单中:
```
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
```
在该示例中,我们创建了回调函数 donothing()并将每个命令链接到它以简化操作。 使用 add_comment()函数添加一个选项。 我们调用 add_cascade()将此菜单列表添加到特定列表。
[下载 tkinter 示例](/download-tkinter-examples)
\ No newline at end of file
# Tk 小部件
> 原文: [https://pythonspot.com/tk-widgets/](https://pythonspot.com/tk-widgets/)
[Tkinter](https://pythonspot.com/tkinter/) 有几个小部件,包括:
* 标签
* 编辑文字
* 图片
* 按钮(之前讨论过)
在本文中,我们将展示如何使用其中的一些 Tkinter 小部件。 请记住,Python 2.x 和 3.x 的 Tkinter 略有不同
**相关课程**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
**标签** 要创建标签,我们只需调用 Label()类并将其打包。 padx 和 pady 是水平和垂直填充。
```
from Tkinter import *
root = Tk()
root.title('Python Tk Examples @ pythonspot.com')
Label(root, text='Python').pack(pady=20,padx=50)
root.mainloop()
```
**EditText(条目小部件)** 要获取用户输入,可以使用条目小部件。
```
from Tkinter import *
root = Tk()
root.title('Python Tk Examples @ pythonspot.com')
var = StringVar()
textbox = Entry(root, textvariable=var)
textbox.focus_set()
textbox.pack(pady=10, padx=10)
root.mainloop()
```
结果:
![tk entry](img/37a3257ed2c7f13f0b141e9c9aa72d3e.jpg) tk entry
**图像** Tk 具有一个小部件来显示图像,即 PhotoImage。 加载图像非常容易:
```
from Tkinter import *
import os
root = Tk()
img = PhotoImage(file="logo2.png")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
```
结果:
![python tk image](img/b572dd0f882ff709fb5896b3f7c9905f.jpg) python tk image
**GUI 编辑器** Tkinter GUI 编辑器的概述可以在这里找到: [http://wiki.tcl.tk/4056](https://wiki.tcl.tk/4056)
[下载 tkinter 示例](/download-tkinter-examples)
\ No newline at end of file
# TkInter 消息框
> 原文: [https://pythonspot.com/tk-message-box/](https://pythonspot.com/tk-message-box/)
[**Tkinter**](https://pythonspot.com/tkinter/) tkMessageBox 具有多种显示**消息框**的方法。
适用于 Python 2.7 的 [**Tkinter**](https://pythonspot.com/tkinter/) 和 Python 3 之间略有不同。 要找到您的 Python 版本,请尝试以下命令之一:
```
python --version
python3 --version
```
**相关课程**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
### Tkinter 消息框
![Tkinter Message box](img/e9d03180e4231af35183a0c4f9ff6277.jpg) TkMessage boxTo show a minimalistic ![tkinter-dialog](img/cada3d59a1bd4887694d8ded4576f519.jpg) Tk messagebox dialog
Tkinter 包括其他几个消息框:
* showerror()
* showwarning()
* showinfo()
<u>Python 3.x</u>
```
import tkinter
from tkinter import messagebox
# hide main window
root = tkinter.Tk()
root.withdraw()
# message box display
messagebox.showerror("Error", "Error message")
messagebox.showwarning("Warning","Warning message")
messagebox.showinfo("Information","Informative message")
```
<u>Python 2.7</u>
```
import Tkinter
import tkMessageBox
# An error box
tkMessageBox.showerror("Error","No disk space left on device")
# A warning box
tkMessageBox.showwarning("Warning","Could not start service")
# An information box
tkMessageBox.showinfo("Information","Created in Python.")
```
您可能会喜欢: [Tkinter 问题对话框](https://pythonspot.com/tkinter-askquestion-dialog/)[更多 Tkinter](https://pythonspot.com/tkinter/)
[下载 tkinter 示例](/download-tkinter-examples)
\ No newline at end of file
# Tkinter tkFileDialog 模块
> 原文: [https://pythonspot.com/tk-file-dialogs/](https://pythonspot.com/tk-file-dialogs/)
`tkFileDialog`是具有打开和保存对话框功能的模块。 无需自己在 [Tkinter GUI](https://pythonspot.com/tkinter/) 中实现。
**相关课程**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
**概述** 文件对话框的概述:
## Tkinter 打开文件
`askopenfilename`函数创建文件对话框对象。 扩展名显示在表格的底部(文件类型)。 下面的代码将仅显示对话框并返回文件名。 如果用户按下取消,则文件名为空。 在 Windows 计算机上,将 initialdir 更改为“ C:\”
**Python 2.7 版本:**
| 功能 | 参量 | 目的 |
| --- | --- | --- |
| .askopenfilename | 目录,标题,扩展名 | 要**打开**文件:要求选择现有文件的对话框。 |
| .asksaveas 文件名 | 目录,标题,扩展名) | 要**保存**文件:要求创建或替换文件的对话框。 |
| .ask 目录 | 没有 | 到**打开目录** |
|
```
from Tkinter import *from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
```
|
**Python 3 版本:**
```
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
```
这是一个示例(在 Linux 上):
![tkfiledialog Tkinter askopenfilename](img/2c7923eec25e9f598b1f2667df933487.jpg) tkfiledialog Tkinter askopenfilename
## Tkinter 保存文件
The `asksaveasfilename` function prompts the user with a save file dialog.
**Python 2.7 版本**
```
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.filename = tkFileDialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
```
**Python 3 版本**
```
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
```
## Tkinter 打开目录
The `askdirectory` presents the user with a popup for directory selection.
**Python 2.7 版本**
```
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.directory = tkFileDialog.askdirectory()
print (root.directory)
```
![tkinter-askdirectory](img/e1fe0af3cb6c0d5c97380258734cdce9.jpg) tkinter askdirectory
[下载 tkinter 示例](/download-tkinter-examples)
\ No newline at end of file
# Tk 下拉示例
> 原文: [https://pythonspot.com/tk-dropdown-example/](https://pythonspot.com/tk-dropdown-example/)
[Tkinter](https://pythonspot.com/tkinter/) 支持下拉菜单。 这类似于操作系统上的标准组合框。
该小部件称为 **OptionMenu** ,所需的参数为:帧,tk 变量和带有选择项的字典。
![tk dropdown menu](img/19e10ff770d93deeffd983bf09f95bdc.jpg)
**相关课程:**
* [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)
## Tkinter 下拉示例
The example below creates a Tkinter window with a combobox.
```
from Tkinter import *
import Tkinter as ttk
from ttk import *
root = Tk()
root.title("Tk dropdown example")
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
# Create a Tkinter variable
tkvar = StringVar(root)
# Dictionary with options
choices = { 'Pizza','Lasagne','Fries','Fish','Potatoe'}
tkvar.set('Pizza') # set the default option
popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Choose a dish").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
# on change dropdown value
def change_dropdown(*args):
print( tkvar.get() )
# link function to change dropdown
tkvar.trace('w', change_dropdown)
root.mainloop()
```
首先创建一个 Tk 对象,并将其传递给使用 Frame()创建的 tkinter 框架
```
root = Tk()
root.title("Tk dropdown example")
mainframe = Frame(root)
```
将一个网格添加到框架,该框架将容纳组合框。
```
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
```
弹出菜单包含在变量选项中定义的选项列表。 使用以下行创建一个 Tkinter 变量:
```
tkvar = StringVar(root)
```
变量的默认值是使用.set()方法设置的。 我们使用以下方法创建 Tkinter 组合框:
```
popupMenu = OptionMenu(mainframe, tkvar, *choices)
```
并将回调方法 change_dropdown 链接到此组合框。
\ No newline at end of file
# wxPython 窗口
> 原文: [https://pythonspot.com/wxpython-window/](https://pythonspot.com/wxpython-window/)
wxPython 是用于 Python 编程语言的 GUI 工具箱。 [wxPython](https://pythonspot.com/wx/) 可用于创建[图形用户界面(GUI)](https://pythonspot.com/gui)
用 wxPython 制作的应用程序在所有平台上都有本机外观。 与具有自定义 QT 或 Tk 外观的 QT 或 Tk 不同,该应用程序将显示为本机应用程序。 它可以在所有主要的桌面平台上运行。
当前支持的操作系统是 Microsoft Windows(32 位),大多数 Unix 或类 Unix 系统以及 Macintosh OSX。
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
wxPython 模块基于 C ++ GUI 库 wxWidgets。
## wxPython 窗口
To open a window with wxPython, run the code below:
```
#!/usr/bin/python
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.Show()
app.MainLoop()
```
wx.App()行创建一个应用程序对象。 每个 [wx](https://pythonspot.com/wx/) 程序都需要具有一个.App()对象。
wx.Frame()方法返回一个可以包含小部件的新窗口。
app.Mainloop()将应用程序置于主循环中并侦听事件。
**窗口大小和位置** 您可以使用 SetDimensions()函数设置位置和大小:
```
#!/usr/bin/python
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,640,480)
frame.Show()
app.MainLoop()
```
该函数的参数为​​:x(左),y(上),宽度和高度。 该功能不仅可以设置屏幕分辨率,还可以设置屏幕上的位置。
**将窗口居中** 要将窗口置于屏幕调用的中心:
```
frame.Centre()
```
\ No newline at end of file
# wxPython 按钮
> 原文: [https://pythonspot.com/wxpython-buttons/](https://pythonspot.com/wxpython-buttons/)
要创建按钮,只需调用 wx.Button()。 使用 wx.Button()创建按钮时,将面板解析为第一个参数很重要。 我们将其附加到面板上,因为将其附加到框架上将使其全屏显示。
面板使您可以选择将小部件放置在窗口中的任何位置。 参数(10,10)是面板上的位置。 id 参数是必需的,但它等于-1(wx.ID_ANY == -1)。 第三个参数是按钮上的文本。
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
您可以使用下面的代码在 [wxPython](https://pythonspot.com/wx/) 中创建一个按钮:
```
#!/usr/bin/python
import wx
def onButton(event):
print "Button pressed."
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)
panel = wx.Panel(frame, wx.ID_ANY)
button = wx.Button(panel, wx.ID_ANY, 'Test', (10, 10))
button.Bind(wx.EVT_BUTTON, onButton)
frame.Show()
frame.Centre()
app.MainLoop()
```
如果按下按钮,则调用 onButton()函数。 我们将其与 button.Bind(wx.EVT_BUTTON,onButton)绑定(连接)。
输出:
![wx button](img/63f4d90dfe1598c08abff7ee025b9a0b.jpg) Buton created with [wxPython](https://pythonspot.com/wx/)
**按钮上的图像** wxPython 支持在按钮上使用图像。 只需稍作更改即可在按钮上显示图像。 虽然该函数称为 wx.BitmapButton,但它支持其他图像格式。
```
bmp = wx.Bitmap("call-start.png", wx.BITMAP_TYPE_ANY)
button = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bmp,
size=(bmp.GetWidth()+10, bmp.GetHeight()+10))
```
第一行加载图像,第二行创建按钮。
完整代码:
```
#!/usr/bin/python
import wx
def onButton(event):
print "Button pressed."
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,70)
panel = wx.Panel(frame, wx.ID_ANY)
bmp = wx.Bitmap("call-start.png", wx.BITMAP_TYPE_ANY)
button = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bmp,
size=(bmp.GetWidth()+10, bmp.GetHeight()+10))
button.Bind(wx.EVT_BUTTON, onButton)
button.SetPosition((10,10))
frame.Show()
frame.Centre()
app.MainLoop()
```
输出:
![wxButton](img/67a209e3d95dcfc3bcf10be8ee22a065.jpg) wxButton
\ No newline at end of file
# wxPython 对话框
> 原文: [https://pythonspot.com/wxpython-dialogs/](https://pythonspot.com/wxpython-dialogs/)
要使用[显示对话框,wxPython](https://pythonspot.com/wx/) 仅需要几行代码。 我们将在下面演示。 我们将讨论信息对话框,简单对话框,错误对话框,警告对话框等。
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
**信息对话框** 信息对话框可以用一行代码显示:
```
import wx
app = wx.App()
wx.MessageBox('Pythonspot wxWidgets demo', 'Info', wx.OK | wx.ICON_INFORMATION)
```
第一个参数是要显示的实际文本。 第二个是标题,最后一个参数告诉 wx 显示信息图标和按钮。
输出:
![wx dialog](img/060aff2419f3f914c11c28c7e8aad94d.jpg) wx dialog
**更多对话框:警告对话框,错误对话框和默认对话框** 通过修改参数,您可以轻松创建其他类型的模拟日志。 下面的例子:
```
import wx
app = wx.App()
# simple dialog
wx.MessageBox('A dialog', 'Title', wx.OK)
# warning dialog
wx.MessageBox('Operation could not be completed', 'Warning', wx.OK | wx.ICON_WARNING)
# error dialog
wx.MessageBox('Operation could not be completed', 'Error', wx.OK | wx.ICON_ERROR)
```
输出(仅对话框之一):
![wxDialog](img/ff4ca6bf3d6ff81f610c0b9de5338c3f.jpg) wxDialog
**问题对话框** Wx 可用于创建问题对话框(是/否)。 示例代码:
```
import wx
app = wx.App()
dlg = wx.MessageDialog(None, "Do you want to update?",'Updater',wx.YES_NO | wx.ICON_QUESTION)
result = dlg.ShowModal()
if result == wx.ID_YES:
print "Yes pressed"
else:
print "No pressed"
```
输出:
![wxDialog](img/7874a6d1f9758b18ee1ef3d3e4f58334.jpg) wxDialog
\ No newline at end of file
# wxPython 文件对话框
> 原文: [https://pythonspot.com/wxpython-file-dialog/](https://pythonspot.com/wxpython-file-dialog/)
几乎每个可以打开一个或多个文件的桌面应用程序都有一个文件对话框。
创建一个打开的文件对话框似乎是一个非常复杂的窗口:它包含按钮,位置,标签和许多其他小部件。 而且,此打开文件对话框的外观在每个平台上都不同:Mac OS,Windows 等。
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
在 wxPython 的模块配备了开放式的文件对话框,可以用几个函数的调用来创建。
![wxPythonOpenFile](img/1d17f5d6e0c394ba2f1d574baf74c7b0.jpg) [wxPython](https://pythonspot.com/wx/) Open File Dialog
## wxPython 文件对话框
The example below creates a file dialog with a native appearance using wxPython:
```
#!/usr/bin/python
import wx
def onButton(event):
print "Button pressed."
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)
# Create open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "",
"Python files (*.py)|*.py",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
openFileDialog.ShowModal()
print(openFileDialog.GetPath())
openFileDialog.Destroy()
```
要使用 [wxPython](https://pythonspot.com/wx/) 创建文件对话框,我们可以简单地调用 wx.FileDialog()。 此方法的定义是:(父,消息,defaultDir,defaultFile,通配符,样式,pos) 我们用以下参数调用此方法:
```
wx.FileDialog(frame, "Open", "", "","Python files (*.py)|*.py",wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
```
(未指定默认目录或默认文件)。
showModal()方法显示窗口:
```
openFileDialog.ShowModal()
```
如果选择一个,则命令 openFileDialog.GetPath()返回文件的完整路径。
\ No newline at end of file
# wxPython 输入对话框
> 原文: [https://pythonspot.com/wxpython-input-dialog/](https://pythonspot.com/wxpython-input-dialog/)
输入对话框可让您的用户给您反馈或输入。 它们偶尔会出现在桌面应用程序中。
wxPython 支持输入对话框,它们包含在框架中。 典型的 wxPython 对话框如下所示:
![wx input](img/38adcfbb184729e5d1d74b09ba622436.jpg) input dialog made with wxPython
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
## wxPython 输入对话框
The example code below creates an input dialog with wxPython:
```
#!/usr/bin/python
import wx
def onButton(event):
print "Button pressed."
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)
# Create text input
dlg = wx.TextEntryDialog(frame, 'Enter some text','Text Entry')
dlg.SetValue("Default")
if dlg.ShowModal() == wx.ID_OK:
print('You entered: %s\n' % dlg.GetValue())
dlg.Destroy()
```
可以使用以下函数将 [wxPython](https://pythonspot.com/wx/) 文本框添加到窗口:
```
wx.TextEntryDialog(frame, 'Enter some text','Text Entry')
```
其中第一个参数是框架,第二个参数是标签,最后一个参数是窗口标题。
下面的函数显示对话框,并等待用户按下按钮之一:
```
dlg.ShowModal()
```
您可以通过选择以下按钮之一来按下按钮:
```
wx.OK
wx.CANCEL
```
(结果是其中之一)
给出输入后,可以使用 dlg.GetValue()函数获取输入文本。
\ No newline at end of file
# wxPython 选项卡
> 原文: [https://pythonspot.com/wxpython-tabs/](https://pythonspot.com/wxpython-tabs/)
尽管出于简单性原因,我们并未在 [wxPython](https://pythonspot.com/wx/) 系列中大量使用面向对象,但是我们无法解决它。 在本教程中,您将学习如何使用 [wxPython](https://pythonspot.com/wx/) 创建选项卡界面。
**相关课程:** [使用 wxPython 创建 GUI 应用程序](https://gum.co/qapqB)
Mainframe 类创建框架,就像前面的示例一样。 其他类别是选项卡的内容。 我们在主框架中创建一个面板和笔记本(标签夹)。 然后我们创建标签对象:
```
tab1 = TabOne(nb)
tab2 = TabTwo(nb)
...
```
我们使用以下方法将其连接到标签夹:
```
nb.AddPage(tab1, "Tab 1")
nb.AddPage(tab2, "Tab 2")
...
```
完整代码:
```
import wx
# Define the tab content as classes:
class TabOne(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the first tab", (20,20))
class TabTwo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the second tab", (20,20))
class TabThree(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the third tab", (20,20))
class TabFour(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the last tab", (20,20))
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="wxPython tabs example @pythonspot.com")
# Create a panel and notebook (tabs holder)
p = wx.Panel(self)
nb = wx.Notebook(p)
# Create the tab windows
tab1 = TabOne(nb)
tab2 = TabTwo(nb)
tab3 = TabThree(nb)
tab4 = TabFour(nb)
# Add the windows to tabs and name them.
nb.AddPage(tab1, "Tab 1")
nb.AddPage(tab2, "Tab 2")
nb.AddPage(tab3, "Tab 3")
nb.AddPage(tab4, "Tab 4")
# Set noteboook in a sizer to create the layout
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
```
输出:
![wxTabs](img/5a58343f3bd5e027d97e90721b1c4a53.jpg) wxTabs
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册