В моем приложении PyGTK я прошу пользователя найти файл, чтобы с ним можно было выполнять операции. Приложение запрашивает у пользователя файл и передает это имя файла необходимым методам. К сожалению, при вызове метода gtk.dispose()
в этом диалоговом окне он просто зависает до тех пор, пока метод, вызываемый для выполнения файлового ввода-вывода, не будет завершен. Я даже пытался поместить манипуляции с файлами в другой поток, но это не дало никакого эффекта.
Моя отступная цель состоит в том, чтобы программа отображала диалоговое окно для пользователя, информирующего его о том, что файл, который он выбрал для манипуляции, имеет место. В текущей реализации диалоговое окно появляется после удаления gtk.FileChooserDialog
.
Ниже мой код:
def performFileManipulation(self, widget, data=None):
# Create the file chooser dialog:
dialog = gtk.FileChooserDialog("Open..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
# Display the file selector and obtain the response back
response = dialog.run()
# If the user selected a file, then get the filename:
if response == gtk.RESPONSE_OK:
dataLocation = dialog.get_filename()
# If the file was not chosen, then just close the window:
else:
print "Closed, no files selected" # Just for now
########## Problem Area ##########
# The dialog is told to get destroyed, however, it hangs here in an
# unresponsive state until the the file-manipulations performed in a new thread
# below are completed. Then, the status dialog (declared below) is displayed.
dialog.destroy() # Close the dialog.
## Show a dialog informing the user that the file manipulation is taking place:
statusDialog = gtk.Dialog("Performing File Operations...", parent=None, flags=0, buttons=None)
statusLabel = gtk.Label("Performing File Operations.\nPlease wait...")
statusLabel.set_justify(gtk.JUSTIFY_CENTER)
statusLabel.show()
statusDialog.vbox.pack_start(statusLabel, True, True, 0)
statusDialog.set_default_size(350, 150)
statusDialog.show()
# Create the thread to perform the file conversion:
errorBucket = Queue.Queue() # Make a bucket to catch all errors that may occur:
theFileOperationThread = doStuffToTheFile(dataLocation, errorBucket) # Declare the thread object.
## Perform the file operations:
theFileOperationThread.start() # Begin the thread
# Check on the thread. See if it's still running:
while True:
theFileOperationThread.join(0.1)
if theFileOperationThread.isAlive():
continue
else:
break
# Check if there was an error in the bucket:
try:
errorFound = errorBucket.get(False)
# If no errors were found, then the copy was successful!
except Queue.Empty:
pass
# There was an error in the bucket! Alert the user
else:
print errorFound
statusDialog.destroy()
Обратите внимание, что этот код еще не завершен, например, он еще неправильно обрабатывает пользователя, не выбравшего файл и отменившего операцию.
РЕДАКТИРОВАТЬ: При дальнейшем расследовании возникла проблема с потоками в PyGTK. Проблема возникает в цикле while True
. Я заменил этот код на time.sleep(15)
, и аналогичным образом диалоговое окно выбора файла приостановится. Это довольно странное поведение, и все должно работать внутри другого потока. Я предполагаю, что теперь вопрос заключается в том, чтобы выяснить, как разместить диалоговое окно выбора файла внутри его собственного потока.