我有一些代码要求用户输入他们要加密的单词,然后程序会加密单词并将其显示在标签上。 我想知道为什么以下代码有效:
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
encr = "".join([enc.get(ch, ch) for ch in string])
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = encr
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
但如果我将string = 'hello world'
(这是我想要做的)更改为string = entry.get()
,则不会显示任何内容on
new_message`。另外,
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + "has been encrypted into the following: ")
不会显示用户在输入框中输入的内容,因此我几乎100%确定我误用了entry.get()
功能。
答案 0 :(得分:2)
您实际上需要在entry.get()
下设置display_encrypt()
。
每按一次encrypt_confirm
按钮,它就会调用display_encrypt
,然后每次用户按下时,entry
都可以获取当前字符串。
我编辑了你的代码,似乎工作正常。
请注意,我已删除string
和encr
,因为它们现在是冗余变量。
import tkinter
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)
enc = dict(zip(letters,encryption_code))
string = 'hello world'
def encrypt():
encrypt_label.pack()
entry.pack()
encrypt_confirm.pack()
encrypt_button.destroy()
def display_encrypt():
display_enc = "".join([enc.get(ch, ch) for ch in entry.get()])
encrypted_label.pack()
new_message.config(text=str(display_enc))
new_message.pack()
encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))
window.mainloop()
答案 1 :(得分:0)
在用户有机会输入任何内容之前,您正在呼叫entry.get()
。您需要调用它并重置标签以响应事件,例如用户按下< Return>,单击按钮等。