【问题标题】:Converting a Python argparse CLI program into a GUI with Tkinter?使用 Tkinter 将 Python argparse CLI 程序转换为 GUI?
【发布时间】:2017-04-26 14:08:42
【问题描述】:

我有一个简单的基于 CLI 的程序,我想添加一个 GUI。理想情况下,我也希望保留通过 CLI 运行此脚本的能力。如果可以做到这一点,解决此问题的最佳方法是什么?免责声明:我对 Tkinter 比较陌生!

from argparse import ArgumentParser
from ipaddress import IPv4Network

def Main():
    """ Main Program """
    parser = ArgumentParser(
        description='Provided a list of IP addresses, format and output the correct fortigate commands to create them')
    parser.add_argument('VDOM', help='Specify a VDOM', type=str)
    parser.add_argument(
        'File', help='Specify a file.  Each entry should be on its own line, and have no extra characters', typ=str)
    args = parser.parse_args()

    with open(args.File, 'r') as input_file:
        array = input_file.read().splitlines()

    with open(args.vdom + '.txt', 'w') as output_file:
        output_file.write("config vdom\n")
        output_file.write("edit %s\n" % str(args.vdom))
        output_file.write("config firewall address\n\n")

        for i in range(0, len(array)):
            try:
                ip_addr = IPv4Network(array[i])
                generateip(ip_addr, output_file)
            except ValueError:
                url = array[i]
                generateurl(url, output_file)


def generateip(ip_addr, output_file):
    """
    Generate a single IP address object.

    ip_addr -- IP address network object
    output_file -- an output text file
    """
    output_file.write("edit \"%s\"\n" % str(ip_addr.with_prefixlen))
    output_file.write("set color 1\n")
    output_file.write("set subnet %s %s\n" %
                  (str(ip_addr.network_address), str(ip_addr.netmask)))
    output_file.write("next\n\n")


def generateurl(url, output_file):
    """
    Generate a single URL address object.

    url -- A valid URL string
    output_file -- an output text file
    """

    output_file.write("edit %s\n" % url)
    output_file.write("set color 1\n")
    output_file.write("set type fqdn\n")
    output_file.write("set fqdn %s\n" % url)
    output_file.write("next\n\n")


if __name__ == '__main__':
    Main()

【问题讨论】:

  • 显而易见的答案是“创建一个创建 gui 的函数,并且只有在用户包含 --gui 选项时才调用该函数”。您在寻找不同的东西吗?
  • 啊,这是个好主意。但是,让我更好地解释一下我的需求。目标是最终在工作中使用该工具。我在 NOC 类型的环境中工作,这里的大多数人都没有安装 python。我打算把它变成一个没有任何依赖关系的可执行文件。我想为自己和其他几个同事维护 CLI 版本。如果我需要两个单独的程序,我也可以走这条路。

标签: python user-interface tkinter command-line-interface argparse


【解决方案1】:

查看https://github.com/chriskiehl/Gooey。这将自动将您的 ArgParser 参数转换为 GUI。 GUI 将依赖于代码,因此程序的根目录仍然依赖于 CLI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2021-09-24
    • 1970-01-01
    • 2013-06-22
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多