littlewhitecloud / TkTerminal

A terminal emulator widget written in Python using tkinter
MIT License
15 stars 2 forks source link

After typing return, the terminal adds an extra line (one too many) #3

Closed Moosems closed 1 year ago

Moosems commented 1 year ago

I fixed it with the following:

    def loop(self, _: Event):
        """Create an input loop"""
        cmd = self.text.get(f"{self.index}.0", "end-1c")
        cmd = cmd.split(">")[-1]

        returnlines = popen(cmd)
        returnlines = returnlines.readlines()

        self.text.insert("insert", "\n")
        self.index += 1
        for line in returnlines:
            self.text.insert("insert", line)
            self.index += 1

        # Remove the next two lines that cause the extra newlines
        self.text.insert("insert", f"PS {getcwd()}>")
        return "break"  # Prevent the default newline character insertion
Moosems commented 1 year ago

In this fix here is the full context:

from tkinter import Event, Tk, Text
from os import popen, getcwd

class Terminal(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.geometry("1000x515")

        self.update()
        self.text = Text(self, background="#2B2B2B" , insertbackground="#DCDCDC", selectbackground="#b4b3b3", relief="flat", foreground="#cccccc")
        self.text.configure(font = ("Cascadia Code", 10, "normal")) # Link to settings later
        self.text.pack(expand=True, fill="both")
        self.index = 1

        self.text.insert("insert", f"PS {getcwd()}>")
        self.text.bind("<KeyPress-Return>", self.loop)

    def loop(self, _: Event):
        """Create an input loop"""
        cmd = self.text.get(f"{self.index}.0", "end-1c")
        cmd = cmd.split(">")[-1]

        returnlines = popen(cmd)
        returnlines = returnlines.readlines()

        self.text.insert("insert", "\n")
        self.index += 1
        for line in returnlines:
            self.text.insert("insert", line)
            self.index += 1

        # Remove the next two lines that cause the extra newlines
        self.text.insert("insert", f"PS {getcwd()}>")
        return "break"  # Prevent the default newline character insertion

example = Terminal()
example.mainloop()