1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Read input with Tkinter

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 14:13.

  1. Stack

    Stack Membro Participativo

    My goal is to create a Gui that will run the script using a button, I have succeeded. Next, I want the gui to be able to show the output from that script and the ability for the user to respond to it. So the question is: How to create a text field in the gui that could display the inputs from the script and handle receiving the responses, which would then be sent back to the script.

    The script which I want open with button:

    def choose_assignment():

    print("1. Mixing two liquids.")
    print("2. Dividing a larger volume into x beakers.")
    print("To select, enter a digit without a dot on the following line:")

    assignment = int(input("Write the digit you choose: "))
    print(f"You chose option {assignment}.")
    a = input("ahoj: ")
    print(a)
    if __name__ == "__main__":
    time.sleep(1) # Simulate some delay
    choose_assignment()


    So I simply want the text box in the gui to show the following when it is run:


    1. Mixing two liquids.

    2. Dividing a larger volume into x beakers.

    To select, enter a digit without a dot on the following line:eek:r



    Write the digit you choose:



    User can answered, for example with 1 so gui shows


    You chose option 1

    Ahoj:



    And so on...

    I have tried this, but it does not work, help please. It doesn't show any error, but it can only show the print from the script, not the content of the input.

    import tkinter as tk
    from tkinter import scrolledtext
    import subprocess
    import threading

    class ScriptRunnerGUI:
    def __init__(self, root):
    self.root = root
    self.root.title("Script Runner")

    # Create a scrolled text widget to display script output
    self.text_area = scrolledtext.ScrolledText(root, width=80, height=20)
    self.text_area.pack(pady=10)

    # Create a button to start the script
    self.start_button = tk.Button(root, text="Start Script", command=self.run_script)
    self.start_button.pack(pady=10)

    # Placeholder for the subprocess
    self.process = None
    self.is_waiting_for_input = False # Track if we are waiting for input

    # Bind the <Return> key to send input from the text area
    self.text_area.bind("<Return>", self.send_input)

    def run_script(self):
    # Disable the start button to avoid multiple starts
    self.start_button.config(state=tk.DISABLED)
    self.text_area.delete(1.0, tk.END) # Clear the text area
    self.display_output("Starting script...\n") # Debug message

    # Start the script in a new thread
    threading.Thread(target=self.execute_script).start()

    def execute_script(self):
    # Path to your script (update this path)
    script_path = 'C:\\Python\\afaina-evobliss-software-68090c0edb16\\automatizace\\script_run.py' # Ensure this is correct

    # Run the script as a subprocess
    self.process = subprocess.Popen(['python', script_path],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    bufsize=1)

    # Continuously read output from the script
    while True:
    output = self.process.stdout.readline() # Read output line by line
    if output == '' and self.process.poll() is not None:
    break # Exit if the process has finished

    self.display_output(output) # Display output in the text area

    # Check if the script is asking for input
    if "enter a digit" in output.lower():
    self.is_waiting_for_input = True
    self.display_output("Write the answer here:...\n") # Indicate waiting
    break # Wait for input

    # Re-enable the start button when the process ends
    self.start_button.config(state=tk.NORMAL)

    def display_output(self, message):
    # Display script output in the text area
    self.text_area.insert(tk.END, message)
    self.text_area.see(tk.END)

    def send_input(self, event=None):
    if self.is_waiting_for_input:
    input_text = self.text_area.get("end-2c linestart", "end-1c") # Get the last line for input
    user_input = input_text.strip() + "\n" # Prepare the input to send

    if self.process:
    self.process.stdin.write(user_input) # Send input to the script
    self.process.stdin.flush() # Ensure it's sent immediately

    self.is_waiting_for_input = False # Reset the flag
    self.text_area.delete("end-2c", "end") # Clear the input line

    # Continue reading output
    threading.Thread(target=self.continue_reading_output).start()

    def continue_reading_output(self):
    # Continue reading output after sending input
    while self.process.poll() is None:
    output = self.process.stdout.readline() # Read output line by line
    if output:
    self.display_output(output) # Display output in the text area

    if __name__ == "__main__":
    root = tk.Tk()
    gui = ScriptRunnerGUI(root)
    root.mainloop()

    Continue reading...

Compartilhe esta Página