问题
I have a simple CLI based program that I would like to add a GUI to. Optimally I would like to retain the ability to have this script run via the CLI as well. If this can be done, what is the best way to approach this? Disclaimer: I am relatively new to 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()
回答1:
Check out https://github.com/chriskiehl/Gooey . This will automatically convert your ArgParser arguments to a GUI. The GUI will be dependent on the code, so the root of your program still depends on the CLI.
来源:https://stackoverflow.com/questions/41088493/converting-a-python-argparse-cli-program-into-a-gui-with-tkinter