我正在尝试在PyQt GUI中的行编辑框中输入文件路径,然后在该文件上执行函数。我希望这可以在同一个GUI中完成。这甚至可能吗?
答案 0 :(得分:0)
当然,您可以在同一个GUI中完成。如果要阻止用户在加载文件之前单击pbutton1
按钮,可以将其属性disabled
设置为True
,并在加载文件后启用该按钮(例如,在调用{时{1}}功能)。我的代码中没有看到任何文件加载说明,因此首先要做的就是将文件内容保存在对象中,因此在button2Pressed
中需要类似的内容:
button2Pressed
现在,当您加载文件时,您需要计算单词。 with open(self.lineedit1.text(), 'r') as my_file:
self.file_content = my_file.readlines()
将文件拆分为单独的行,因此您还必须执行循环来计算所有单词,因此在readlines
中您可以编写例如:
button1Pressed
请注意,上面的代码只会将您的行拆分为空格(self.word_counter = 0
for line in self.file_content:
for word in line.split(' ')
if word == self.lineedit2.text():
counter +=1
)上的单词。如果您想要删除逗号和其他符号,请考虑使用' '
。我希望这会给你一个想法。干杯!
答案 1 :(得分:0)
您的代码需要一些重新排列才能正常工作。要考虑的主要事情是将工作分成几部分,每个部分都做一件事。因此,一个方法读取文件,一个计算单词,一个输出结果等。
以下是对您的示例的基本重写,其中包含一些已做出更改的注释:
import sys, os, string
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# move wordcount function into the class
class Form( QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setWindowTitle("Word Count GUI")
# use placeholder text
self.lineedit2 = QLineEdit()
self.lineedit2.setPlaceholderText('Enter Filename Here')
self.pbutton2 = QPushButton('Press to Load File')
# use placeholder text
self.lineedit1 = QLineEdit()
self.lineedit1.setPlaceholderText("Enter Word Here")
self.pbutton1 = QPushButton("Press for Count")
self.pbuttonQuit = QPushButton("Exit")
# don't forget the layout...
layout = QVBoxLayout()
layout.addWidget(self.lineedit2)
layout.addWidget(self.pbutton2)
layout.addWidget(self.lineedit1)
layout.addWidget(self.pbutton1)
layout.addWidget(self.pbuttonQuit)
self.setLayout(layout)
self.pbutton2.setFocus()
# use new-style connections
self.pbutton1.clicked.connect(self.button1Pressed)
self.pbutton2.clicked.connect(self.button2Pressed)
# connect to self.close to quit
self.pbuttonQuit.clicked.connect(self.close)
# keep a list of lines
self.lines = []
def wordcount(self, word):
total = 0
# iterate over stored lines
for line in self.lines:
line = line.translate(None, string.punctuation)
line = line.lower()
words = line.split()
if word in words:
total += 1
return total
def button1Pressed(self):
x1 = self.lineedit1.text()
x1 = str(x1).lower()
# use the wordcount method
x2 = self.wordcount(x1)
outtext = str(x1) + " appears " + str(x2) + " times in the file."
self.lineedit1.setText(outtext)
def button2Pressed(self):
# this reads the file and stores the lines
g = str(self.lineedit2.text())
g = os.path.join('/Users/xxx/Documents/Python', g)
try:
with open(g) as stream:
self.lines = stream.readlines()
except EnvironmentError as exception:
print('ERROR: could not read file:')
print(' : %s' % exception)
self.lines = []
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()