Чтение ввода с помощью TkinterPython

Программы на Python
Ответить
Anonymous
 Чтение ввода с помощью Tkinter

Сообщение Anonymous »

Моя цель — создать графический интерфейс, который будет запускать скрипт с помощью кнопки, мне это удалось. Далее, я хочу, чтобы графический интерфейс мог отображать выходные данные этого сценария и возможность пользователя реагировать на него.
Итак, вопрос в следующем: как создать текстовое поле в gui, который мог бы отобразить входные данные из сценария и обработать получение ответов, которые затем будут отправлены обратно в сценарий.
Скрипт, который я хочу открыть с помощью кнопки:
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()

Поэтому я просто хочу, чтобы текстовое поле в графическом интерфейсе при запуске отображало следующее:

1. Mixing two liquids.

2. Dividing a larger volume into x beakers.

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

Write the digit you choose:


Пользователь может ответить, например, цифрой 1, чтобы отображался графический интерфейс

You chose option 1

Ahoj:


И так далее...
Я пробовал это, но это не работает, помогите, пожалуйста.
Это не так. показать любую ошибку, но он может отображать только вывод из сценария, а не содержимое ввода.
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 key to send input from the text area
self.text_area.bind("", 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()



Подробнее здесь: https://stackoverflow.com/questions/790 ... th-tkinter
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»