微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python tkinter 编码器,但程序太长了

如何解决Python tkinter 编码器,但程序太长了

所以这个想法是制作一个编码器,我的意思是当用户在称为文本的标签中写入例如“a”时,程序粘贴结果为“}”等等。

问题是我是否必须为字母表中的每个字母和标签文本中的每个位置都写“if”,我的意思是如果 user_code[0] 如果用户代码[1] 等等

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,height=15 )
result.pack(side=tk.RIGHT)


#  ):


root.mainloop()

解决方法

不,您可以使用 for 循环遍历 user_code 的字母,并创建字典将一个字母映射到另一个字母。

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)

如果您有许多不同的字母编码并且不想输入太多逗号、引号、冒号,您甚至可以像这样创建字典:

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))}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。