[英]How to run a function only once in GUI
I want to run the function removeHi(self)
only once in my program, how to accomplish this.我想在我的程序中只运行一次
removeHi(self)
函数,如何做到这一点。 Please advise me.请给我提意见。 My entire code below:
我的整个代码如下:
import sys
from PyQt5.QtWidgets import *
from functools import wraps
class TestWidget(QWidget):
gee = ''
def __init__(self):
global gee
gee = 'Hi'
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea=QTextBrowser(self)
self.outputArea.append(gee)
self.helloButton=QPushButton("reply", self)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.outputArea)
self.layout().addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
self.outputArea.clear()
def sayHello(self):
yourName, okay=QInputDialog.getText(self, "whats your name?", "name")
if not okay or yourName=="":
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi,{yourName}")
app=QApplication(sys.argv)
testWidget=TestWidget()
testWidget.show()
sys.exit(app.exec_())
The GUI will show "Hi" when the program runs.程序运行时,GUI 将显示“Hi”。 I want the "Hi" in
QTextBrowser
removed after I push the button reply
, but the program will clear everything in the text browser whenever I clicked the button.我希望在按下按钮
reply
后删除QTextBrowser
中的“Hi”,但只要我单击按钮,程序就会清除文本浏览器中的所有内容。
My goal is: only the first Hi
be removed, and the name from function sayHello(self)
will remain whenever I push the reply
button.我的目标是:只删除第一个
Hi
,只要我按下reply
按钮,函数sayHello(self)
的名称就会保留。
The problem resides in the logic of your program: you should check whether the text must be cleared or not, using a default value that would be changed whenever the dialog changes the output:问题在于程序的逻辑:您应该检查是否必须清除文本,使用默认值,只要对话框更改输出就会更改:
class TestWidget(QWidget):
clearHi = True
def __init__(self):
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea = QTextBrowser()
self.outputArea.append('Hi')
self.helloButton = QPushButton("reply")
layout = QVBoxLayout(self)
layout.addWidget(self.outputArea)
layout.addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
if self.clearHi:
self.outputArea.clear()
def sayHello(self):
yourName, okay = QInputDialog.getText(
self, "whats your name?", "name")
if not okay:
return
self.clearHi = False
if not yourName:
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi, {yourName}")
Note: do not use globals.注意:不要使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.