如何在 Tkinter 中创建一个类似 IDLE 的小型 Python Shell? [英] How can I create a small IDLE-like Python Shell in Tkinter?

查看:35
本文介绍了如何在 Tkinter 中创建一个类似 IDLE 的小型 Python Shell?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个由 Python Shell GUI 控制的东西.

I'm trying to make a thing controlled by a Python Shell GUI.

唯一的问题是,我不知道如何制作整个输入/输出的东西.我只想能够输入一个输入,执行 python 命令并给出 python 命令的输出.我知道 IDLE 是在 Tkinter 中制作的,所以它使用小部件?

The only thing is, I don't know how to make that whole input/output thing. I just want to be able to type an input, execute the python command and give the output of the python command. I know that IDLE is made in Tkinter, so it uses the widgets?

它实际上只是一个输入输入,显示输出"的东西.

It's literally just a "type input, show output" thing.

我试过搜索它,但似乎大多数结果都与命令行有关,这不是我要找的.另一个与我完全一样的问题也不是我的想法.我也尝试查找 IDLE 的源代码,但找不到我要找的内容.

I've tried searching it up but it seems like most of the results are to do with the command line, which isn't what I'm looking for. The only other question that was exactly like mine wasn't what I had in mind, either. I also tried loking up the source code for IDLE but couldn't find what I was looking for.

我找到了一些适用于 Linux 的答案,但我使用的是 Windows 10...

I've found some answers that work for Linux but I'm on Windows 10...

我需要 Tkinter 中的shell",因为在屏幕的一侧将是连接到命令输出的其他东西.

I need the "shell" to be in Tkinter because on one side of the screen will be something else which is connected to the command outputs.

有谁知道用于制作非常简单的 Python shell 的小部件吗?

Does anyone know the widgets used to make a very simple Python shell?

推荐答案

Simple Python Shell/Terminal/Command-Prompt

<小时>
  • ************************ 它字面意思只是一个type input, show输出"的东西.****************************
  • Simple Python Shell / Terminal / Command-Prompt


    • ********************* It's literally just a "type input, show output" thing. ************************
    • import os
      from tkinter import *
      from subprocess import *
      
      
      class PythonShell:
      
          def __init__(self):
              self.master = Tk()
      
              self.mem_cache = open("idle.txt", "w+")
              self.body = None
              self.entry = None
              self.button = None
              self.entry_content = None
      
          @staticmethod
          def welcome_note():
              """
              To show welcome note on tkinter window
              :return:
              """
              Label(text="Welcome To My Python Program [Version 1.0]", font='Arial 12', background="#272626",
                    foreground="white").pack()
      
              Label(text=">> Insert Python Commands <<", font='Arial 12', background="#272626",
                    foreground="white").pack()
      
          def get_text(self):
              """
              This method will perform following operations;
              1- Get text from body
              2- Implies python compilation (treat text as command)
              3- Set Output in Output-Entry
      
              :return: get and set text in body of text box
              """
              content = self.body.get(1.0, "end-1c")
              out_put = self.run_commands(content)
              self.entry_content.set(out_put)
      
          def store_commands(self, command=None):
      
              try:
                  self.mem_cache.write(command + ';')
                  self.mem_cache.close()
      
              except Exception as e:
                  print(e)
      
          def get_stored_commands(self):
              try:
                  with open("idle.txt", "r") as self.mem_cache:
                      self.mem_cache.seek(0)
                      val = self.mem_cache.read()
                      self.mem_cache.close()
                      return val
      
              except Exception as e:
                  print(e)
      
          @staticmethod
          def check_if_file_empty():
              size = os.stat("idle.txt").st_size
      
              if size != 0:
                  return True
              else:
                  return False
      
          def run_commands(self, command):
              """
      
              This method would return output of every command place in text box
              :param command: python command from text box
              :return: output of command
              """
      
              print("Running command: {}".format(command))
              value = None
              new_line_char = command.find('\n')
              semi_colons_char = command.find(';')
              double_quote = command.find('"')
      
              try:
                  if new_line_char != -1:
      
                      if semi_colons_char != -1 & double_quote == -1:
      
                          new_cmd = command.replace("\n", "")
                          cmd_value = '"' + new_cmd + '"'
                          self.store_commands(command)
      
                          value = check_output("python -c " + cmd_value, shell=True).decode()
                      elif semi_colons_char == -1 & double_quote == -1:
      
                          new_cmd = command.replace("\n", ";")
                          cmd_value = '"' + new_cmd + '"'
                          self.store_commands(command)
                          value = check_output("python -c " + cmd_value, shell=True).decode()
      
                      elif double_quote != -1:
      
                          cmd_1 = command.replace('"', "'")
                          new_cmd = cmd_1.replace('\n', ';')
      
                          cmd_value = '"' + new_cmd + '"'
                          self.store_commands(command)
      
                          value = check_output("python -c " + cmd_value, shell=True).decode()
      
                      elif self.body.compare("end-1c", "==", "1.0"):
                          self.entry_content.set("the widget is empty")
      
                  elif self.body.compare("end-1c", "==", "1.0"):
                      value = "The widget is empty. Please Enter Something."
      
                  else:
                      variable_analyzer = command.find('=')
                      file_size = PythonShell.check_if_file_empty()
      
                      if file_size:
                          new_cmd = command.replace('"', "'")
                          cmd_value = '"' + new_cmd + '"'
                          stored_value = self.get_stored_commands()
                          cmd = stored_value + cmd_value
                          cmd.replace('"', '')
      
                          value = check_output("python -c " + cmd, shell=True).decode()
                      elif variable_analyzer != -1:
                          new_cmd = command.replace('"', "'")
                          cmd_value = '"' + new_cmd + '"'
                          self.store_commands(cmd_value)
      
                          value = 'Waiting for input...'
                          pass
                      else:
                          new_cmd = command.replace('"', "'")
                          cmd_value = '"' + new_cmd + '"'
                          value = check_output("python -c " + cmd_value, shell=True).decode()
      
              except Exception as ex:
                  print('>>>', ex)
                  self.entry_content.set('Invalid Command. Try again!!!')
      
              print('>>', value)
              # To Clear Text body After Button Click
              # self.body.delete('1.0', END)
      
              return value
      
          def start_terminal(self):
              """
              Initiate tkinter session to place and run commands
              :return:
              """
              self.master.propagate(0)
              self.master.geometry('750x350')
              self.master.title('Python IDLE')
              self.master.configure(background='#272626')
      
              terminal.welcome_note()
      
              self.body = Text(self.master, height='10', width='75', font='Consolas 12', background="#272626",
                               foreground="white",
                               insertbackground='white')
              # self.body.propagate(0)
              self.body.pack(expand=True)
      
              Label(text=">> Command Output <<", font='Arial 12', background="#272626",
                    foreground="white").pack()
      
              self.entry_content = StringVar()
              self.entry = Entry(self.master, textvariable=self.entry_content, width=50, font='Consolas 16',
                                 background="white",
                                 foreground="black")
              self.entry.pack()
              # self.entry.propagate(0)
      
              self.button = Button(self.master, text="Run Command", command=self.get_text, background="white",
                                   foreground="black",
                                   font='Helvetica 12').pack()
      
              self.master.mainloop()
      
      
      if __name__ == '__main__':
          terminal = PythonShell()
          terminal.start_terminal()
      

      <小时>

      上面给出的python脚本具有以下给定的层次结构;


      The above given python script has following hierarchy as given;

          |import ...      
          |class PythonShell:
              |def __init__(self):...
      
              @staticmethod
              |def welcome_note():...
              |def get_text(self):...
              |def store_commands(self, commmand):...
              |def get_stored_commands(self):...
      
              @staticmethod
              |def check_if_file_empty():
              |def run_commands(self, command):...
              |def start_terminal(self):...
      
          |if __name__ == '__main__':...
      

      <小时>

      工作流程:

      以上代码的基本工作流程如下;


      Workflow:

      The basic workflow for the above code is given as follows;

      • defwelcome_note():... 包括将显示在文本正文之外的标签.

      • def welcome_note():... Includes the Label that will display outside the text body.

      def get_text(self):... 执行两个操作;** 从文本正文中获取文本 ** &** 在输入框中设置输出 **.

      def get_text(self):... Performs two operations; ** Get text from text body ** & ** Set Output in the Entry Box **.

      def store_commands(self, command):... 用于将变量存储到文件中.

      def store_commands(self, command):... Use to store variable into file.

      def get_stored_commands(self):...获取存储在文件中的变量.

      def get_stored_commands(self):... Get variable stored in file.

      def check_if_file_empty():...检查文件大小.

      def run_commands(self, command):... 此方法充当 python 编译器,接受命令、处理并为给定命令生成输出.要运行命令,我建议使用 subprocess-module 因为它提供了更强大的工具来生成新进程并检索它们的结果;使用 python 运行 window-commands 包括各种内置库,例如;

      def run_commands(self, command):... This method act as python compiler that take commands, do processing and yield output for the given command. To run commands, i would recommend to use subprocess-module because it provides more powerful facilities for spawning new processes and retrieving their results; To run window-commands using python includes various builtin libraries such as;

      1. os(详细),2. 子流程(详细) 等

      要结帐哪个更好用,请访问参考:subprocess-module 比操作系统模块.

      To checkout which is better to use, visit reference: subprocess- module is preferable than os-module.

      def start_terminal(self):... 此方法仅涉及启动 tkinter 会话窗口和显示输入和输出窗口的基本布局的功能.

      def start_terminal(self):... This method simply involves the functionality to initiate tkinter session window and show basic layout for input and output window.

      您可以根据需要进一步修改和优化此代码.

      You can further modify and optimize this code according to your requirement.

      这个简单的 tkinter GUI 基于 python shell 执行简单的功能,如 windows-command-prompt.要在命令提示符中直接运行python命令而不进入python终端,我们做的很简单;

      This simple tkinter GUI based python shell perform simple functionality as windows-command-prompt. To run python commands directly in command-prompt without moving into python terminal, we do simple as;

      python -c "print('Hey Eleeza!!!')"
      

      它的结果很简单;

      Hey Eleeza!!!
      

      同样,一次直接运行多行;

      Similarly, to run more than one lines directly at a time as given;

      python -c "import platform;sys_info=platform.uname();print(sys_info)"
      

      它的输出将是;

      My System Info: uname_result(system='Windows', node='DESKTOP-J75UTG5', release='10', version='10.0.18362', machine='AMD64', processor='Intel64 Family 6 Model 142 Stepping 10, GenuineIntel')
      

      <小时>

      所以要使用这个tkinter python shell;

      • 您可以将命令放置为;

      • Either you can place command as;

      import platform
      value=platform.uname()
      print('Value:', value)
      

    • 或者像这样;

    • or like this way;

      import platform;value=platform.uname();
      print('Value:', value)
      

    • 或简单地将命令内联为

    • or simply inline command as

      import platform;value=platform.uname();print('Value:', value)
      

    • 你会得到同样的结果.

      这篇关于如何在 Tkinter 中创建一个类似 IDLE 的小型 Python Shell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆