Search code examples
pythontkinterttkencoder

Python tkinter encoder which but the programme is so long


So the idea is making an encoder i mean when user write for example "a" in label called text the programme paste result for ex "}" and so on.

The question is do i have to write "if" for every letter in alphabet and every place in the label text i mean if user_code[0] if user_code[1] and so on

import tkinter as tk

#making main window
root = tk.Tk()
root.title("Szyfrator")
root.geometry("600x300")

#getting text
def getting_Text():
    user_code = text.get("1.0",'end-1c')
    if user_code[0] == 'a' :
       result.insert(tk.END, '[', 'big')
    if user_code[0] == 'b':
        result.insert(tk.END, ';', 'big')
#UX of the window
right_margin = tk.Frame(root)
right_margin.pack (side=tk.RIGHT, expand =tk.YES , fill=tk.BOTH)
left_margin = tk.Frame(root)
left_margin.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)
#after clicking button function getting_text() is used
button = tk.Button( root , text = "Szyfruj", activebackground = "#FFFFFF", command=getting_Text)
button.pack( side = tk.TOP )
text=tk.Text(root, width=36, height=15 )
text.pack(side= tk.LEFT)
result= tk.Text(root, width=36, height=15 )
result.pack(side=tk.RIGHT)


#  ):


root.mainloop()

Solution

  • No, you can use a for-loop to iterate over the letters of user_code, and create a dictionary to map a letter to another.

    encoded = {
        "a": "[",
        "b": ";"
    }
    
    def getting_Text():
        user_code = text.get("1.0", 'end-1c')
        for letter in user_code:
            try:
                result.insert(tk.END, encoded[letter], 'big')
            except KeyError: # if we don't have an encoding for a letter, a KeyError will be raised which we capture
                print("Oops, no encoding found for letter %s" % letter)
    

    And if you have many different letter encodings and don't want to type in so much commas, quotes, colons, you can even create the dictionary like this:

    letters = "abcdefghijklmnopqrstuvwxyz" # letters and encodings must have the same amount of symbols, else it may give you an IndexError: index out of range
    encodings = "[;]:_-#'+*´`?=)(/&%$§!°^<>"
    encoded = {key: value for key, value in zip(list(letters), list(encodings))}