為了解決封閉的問題,我在這里發布了完整的代碼。
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
form_class = uic.loadUiType(BASE_DIR "./test.ui")[0]
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func)
def func(self, a):
global b
b = a
if __name__ == "__main__" :
app = QApplication(sys.argv)
myWindow = WindowClass()
myWindow.show()
app.exec_()
并且它還需要在同一目錄中的 ui 檔案,
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>298</width>
<height>197</height>
</rect>
</property>
<property name="maximumSize">
<size>
<width>298</width>
<height>197</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="button">
<property name="geometry">
<rect>
<x>100</x>
<y>80</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
在這段代碼中,
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func(1))
def func(self, a):
global b
b = a
這會導致引數錯誤(TypeError: argument 1 has unexpected type 'NoneType')。有什么方法可以使用該功能func嗎?
我嘗試wc = WindowClass()將代碼更改為:
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
wc = WindowClass()
self.button.clicked.connect(wc.func(1))
def func(self, a):
global b
b = a
這會導致致命的初始化錯誤(致命的 Python 錯誤:_Py_CheckRecursiveCall:無法從堆疊溢位中恢復。Python 運行時狀態:已初始化當前執行緒 0x000097e8(最近的呼叫優先):)。
代碼在以下情況下完美運行:
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func)
def func(self):
global b
b = 1
但是,我必須使用func2 個引數。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
嘗試使用部分:
from functools import partial
self.button.clicked.connect(partial(self.func, 1))
我的猜測是 connect 需要一個 0 引數函式。Partial 固定引數并創建一個 0 引數函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/390118.html
上一篇:將函式的回傳值設定為變數js
下一篇:定義函式的位置
