所以我在类中编写一个Python程序,它使用Caesar密码来获取用户输入并将其输出为密文。由于我有更多时间参与这个项目,我计划在Tkinter中为它提供一个GUI。但是当我将生成的密码文本分配给标签时,它不会显示它并将其保持为空白。我是python的菜鸟,甚至更多的是Tkinter,所以我不太热衷于自己解决这些问题。这是代码:
import string
import collections
import random
import tkinter
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Encoder")
root.geometry("500x400")
def caesar(rotate_string, number_to_rotate_by):
upper = collections.deque(string.ascii_uppercase)
lower = collections.deque(string.ascii_lowercase)
upper.rotate(number_to_rotate_by)
lower.rotate(number_to_rotate_by)
upper = ''.join(list(upper))
lower = ''.join(list(lower))
return rotate_string.translate(str.maketrans(string.ascii_uppercase, upper)).translate(str.maketrans(string.ascii_lowercase, lower))
def callback():
print (code)
b = Button(root, text="get", width=10, command=callback)
b.pack()
var = StringVar()
e = Entry(root, textvariable = var)
e.pack()
our_string = e.get()
random_number = random.randint(1,25)
code = caesar(our_string, random_number)
l = Label(root, textvariable=code, anchor=NW, justify=LEFT, wraplength=398)
l.pack()
l.place(relx=0.5, rely=0.5, anchor=CENTER)
root.mainloop()
答案 0 :(得分:1)
您发布的代码存在多个问题。首先,除了打印code
变量之外,您的回调不会执行任何操作。您需要将您的呼叫移至caesar
并将相关代码移至回调中,如此
def callback():
global code
our_string = e.get()
random_number = random.randint(1, 25)
code.set(caesar(our_string, random_number))
我看到的第二个问题是,您需要在StringVar
构造函数中使用textvariable
作为Label
参数,以便让标签自动更新。完成所有操作后,我的代码版本就像
import string
import collections
import random
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Encoder")
root.geometry("500x400")
code = StringVar()
code.set('Hello')
def caesar(rotate_string, number_to_rotate_by):
upper = collections.deque(string.ascii_uppercase)
lower = collections.deque(string.ascii_lowercase)
upper.rotate(number_to_rotate_by)
lower.rotate(number_to_rotate_by)
upper = ''.join(list(upper))
lower = ''.join(list(lower))
return rotate_string.translate(str.maketrans(string.ascii_uppercase, upper)).translate(str.maketrans(string.ascii_lowercase, lower))
def callback():
global code
our_string = e.get()
random_number = random.randint(1, 25)
code.set(caesar(our_string, random_number))
b = Button(root, text="get", width=10, command=callback)
b.pack()
var = StringVar()
e = Entry(root, textvariable=var)
e.pack()
l = Label(root, textvariable=code, anchor=NW, justify=LEFT, wraplength=398)
l.pack()
l.place(relx=0.5, rely=0.5, anchor=CENTER)
root.mainloop()
这似乎符合您的期望。