如何在GUI中仅运行一次功能
我想运行函数removehi(self)
在我的程序中仅一次,如何完成此操作。请告知我。我的整个代码下面:
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_())
GUI将在程序运行时显示“ HI”。我希望在按下按钮回复
后删除qtextBrowser
中的“ hi”,但是每当我单击按钮时,该程序都会清除文本浏览器中的所有内容。
我的目标是:仅删除第一个hi
,而函数sayhello(self)
的名称只要我按下回复
按钮。
I want to run the function removeHi(self)
only once in my program, how to accomplish this. 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. 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.
My goal is: only the first Hi
be removed, and the name from function sayHello(self)
will remain whenever I push the reply
button.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题位于程序的逻辑中:您应该检查是否必须清除文本,使用默认值,每当对话框更改输出时将更改:
注意:do do 不是 使用全球。
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:
Note: do not use globals.