Python 使用PyQt5设计器将按钮集成到现有代码中
所以我试图创建一个按钮来运行上面的程序。我以前用过一个物理按钮,但现在我想做一个数字显示。我已经在QT5 designer上创建了按钮,但似乎无法集成它TL;您可以将现有代码集成到UI,而不是将现有代码集成到UI。如果您只需要一个按钮,那么直接用python编写ui就容易多了,但由于您已经有了ui文件,这个答案就是这样的 我猜,使用PyQt5的pyside2 uic或pyuic将.ui文件转换为python代码 例如,对于带有PySide2的windows cmd:Python 使用PyQt5设计器将按钮集成到现有代码中,python,pyqt5,pyside2,Python,Pyqt5,Pyside2,所以我试图创建一个按钮来运行上面的程序。我以前用过一个物理按钮,但现在我想做一个数字显示。我已经在QT5 designer上创建了按钮,但似乎无法集成它TL;您可以将现有代码集成到UI,而不是将现有代码集成到UI。如果您只需要一个按钮,那么直接用python编写ui就容易多了,但由于您已经有了ui文件,这个答案就是这样的 我猜,使用PyQt5的pyside2 uic或pyuic将.ui文件转换为python代码 例如,对于带有PySide2的windows cmd: from pages imp
from pages import*
import time
import sys
#GPIO Pins Setup
buzzer_motor = 12
#input from physical switch
button = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(button, GPIO.IN, pull_up_down = GPIO.PUD_UP)
#output to motor which is connected to pin 12
GPIO.setup(buzzer_motor, GPIO.OUT)
a = 0
def Mag_Train():
GPIO.output(buzzer_motor, True)
time.sleep(.3)
GPIO.output(buzzer_motor, False)
result = "Success"
print(time.asctime())
time_end = time.asctime()
time.sleep(1)
return [time_end,result]
while(a == 0):
if(GPIO.input(button) == False):
Mag_Train()
# def sayHello():
# print("Push Button Clicked")
# button = True
#
# app = QApplication(sys.argv)
# magazineStart = magazineStart("MAGAZINE START")
# magazineStart.clicked.connect(sayHello)
# magazineStart.show()
# app.exec_()
将main.ui更改为相应的.ui文件位置
要使用生成的python脚本,最好导入并创建它的子类,以备将来可能进行的更改
下面的示例假设您只有一个名为“按钮”的按钮,并用作打开或关闭功能的切换按钮
只需复制粘贴您的逻辑即可运行,将按钮更改为QPushButton的名称并更改时间。睡眠调用event.wait就足够了,但我建议先学习代码
pyside2-uic main.ui > ui_main.py
请注意:
这两种Qt实现都支持Qrunnable,它在内部处理callable的并发运行,但看起来您的任务并不复杂,直接使用线程模块会更直接。
通过在Desiger程序的QPushButton中启用Toggle属性,可以避免重新连接按钮操作,并使用新功能检查按钮是否被切换-但您必须将对线程和事件的引用存储在本地之外。
如果你只有两个按钮——开始、停止,那就容易多了
from PySide2.QtWidgets import QMainWindow, QApplication
from ui_main import Ui_MainWindow
import threading
import sys
def function_to_be_run(event: threading.Event):
while not event.is_set():
# Do your stuff here. We'll just print and wait using event.wait().
print("Alive 'n kickin'")
event.wait(1)
print('Good bye!')
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.released.connect(self.starter)
def stopper(self, thread_event: threading.Event, thread: threading.Thread):
thread_event.set()
thread.join() # Wait for thread to finish
self.pushButton.released.connect(self.starter) # connect button back to starter
def starter(self):
event = threading.Event()
t = threading.Thread(target=function_to_be_run, args=[event])
t.start()
self.pushButton.released.connect(lambda x: self.stopper(event, t)) # connect to stopper so it can stop.
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
def if_button_is_toggle(self):
if self.pushButton.isChecked():
pass # stop thread here
else:
pass # run thread here