Hi to everyone. the question today is the following one:
· I’m trying to read some specific inputs from user in python console in Slicer. For this purpose I use:
def entryLetterReader(prompt):
while True:
try:
user_input = input(prompt)
user_input = user_input.strip() # Eliminar espacios en blanco al principio y al final
if user_input and user_input.isalpha() and len(user_input) == 1:
return user_input
else:
print("Invalid input. Please enter a letter.")
except EOFError:
print("EOFError: End of File reached. Please make sure to provide input.")
In this example I only want to accept the input when it is a letter. The first time my code calls the function works well, and for example if y click enter without type any letter, advises me to put one letter. Although, when my code calls the function for second time this apparently does not work, letting the user click enter and continue.
The code was tested in Spyder API and works fine, any suggestion about it?
When we execute the code in function version, it only works well the first time. Then the following times the code can not manage the exception and pass thru the except without stopping. We tried it in Spyder and PyCharm, and only crashes in Slicer.
You should use a Qt widget, like a QLineEdit with a button or a menu of choices, which you can get signals from. This will integrated with Slicer’s event loop in a way that python’s input function is not.
Slicer did not crash. While Slicer was running your Python commands, the application could not process events, so the application GUI could not respond. There are many ways to avoid this (pump the event loop, use timers, run processing in a subprocess, etc.), but as @pieper suggested above, the right thing to do is to use the GUI of the application for user input.
See Slicer developer tutorials on how to implement a simple Python-scripted module in Slicer that can get all the inputs from the user, run the processing, and display its outputs.
Thanks for your answers @lassoan and @pieper. To be honest, creating interfaces with Qt and similar is a new world for me, I’m not very familiarized with it.
I was reading the documentation that you recommended me, but i’m not sure how to start. My goal is not very ambitious: I need to create a button that until pressed stops the code. When I click the same button, the code should run again. The process of stop and continue should happen multiple times during the execution of the code.
If you could give me some guidelines to start it, I will appreciate it.
You basically just need to set up your code to be event driven rather than depending on a loop to iterate. You could look at the Endoscopy module for example.