我正在尝试使用tkinter创建caesar密码程序,当我尝试将用户的Entry从字符串转换为Int时我得到此错误:AttributeError:' str'对象没有属性' _root'。 我已经尝试过使用' stextentry = int(stextentry)'我知道它的工作原理,但我需要使用该脚本的其他版本的代码来处理另一个程序。我不知道如何摆脱这个错误,所以我希望有人可以帮助我,顺便说一句,这不是家庭作业,也不与学校有任何关系。
from tkinter import *
def Encryption():
ptextentry = ptext.get()
stextentry = stext.get()
stextentry = IntVar(stextentry)# <------------------- Error is here
alpha = "abcdefghijklmnopqrstuvwxyz"
cipher = " "
for c in ptextentry:
if c in alpha:
cipher += alpha[(alpha.index(c)+stextentry) % (len(alpha))]
print (cipher)
global P_Text_E, P_Text_L, S_K_L, S_K_E, plain_text, cctk
cctk = Tk()
ptext = StringVar()
stext = StringVar()
P_Text_L = Label(cctk, text="Enter plain text:").grid(row=0, column=0)
P_Text_E = Entry(cctk, textvariable=ptext).grid(row=0, column=1)
S_K_L = Label(cctk, text="Enter shift key:").grid(row=1, column=0)
S_K_E = Entry(cctk, textvariable=stext).grid(row=1, column=1)
Encrypt_B = Button(cctk, text="Encrypt plain text", command = Encryption).grid(row=2, columnspan =3)
Exit_cctk_B = Button(cctk, text="Exit").grid(row=3, columnspan =3)
cctk.title("Caesar Cipher Program")
cctk.mainloop()**
答案 0 :(得分:1)
stextentry = IntVar(value=stextentry)
没有value=
的单个参数被视为parent
,因此您可以执行
stextentry = IntVar(cctk)
stextentry.set(stextentry)
或
stextentry = IntVar(cctk, stextentry)
但你可以在一行
stextentry = IntVar(value=stext.get())
但现在stextentry
为IntVar
,因此您必须在
stextentry.get()
cipher += alpha[(alpha.index(c) + stextentry.get() ) % (len(alpha))]
BTW:如果你这样做
var = Widget(...).grid(...)
var = Widget(...).pack(...)
然后您将None
分配给var
,因为grid()
/ pack()
始终返回None
你需要分两行
var = Widget(...)
var.grid(...)
或没有变量
Widget(...).grid(...)
编辑:完整代码 - 更具可读性:更好的变量名称,空行。
import tkinter as tk
import string
# --- constants --- (UPPER_CASE names)
ALPHA = string.ascii_lowercase
LENGTH = len(ALPHA)
# --- functions --- (lower_case names)
def encryption():
cipher = ""
for char in plain_text.get():
if char in ALPHA:
cipher += ALPHA[(ALPHA.index(char) + shift_int.get()) % LENGTH]
result_text.set(cipher)
print(cipher)
# --- main ---
cctk = tk.Tk()
cctk.title("Caesar Cipher Program")
plain_text = tk.StringVar()
shift_int = tk.IntVar()
result_text = tk.StringVar()
l = tk.Label(cctk, text="Enter plain text:", anchor="e")
l.grid(row=0, column=0, sticky="e")
e = tk.Entry(cctk, textvariable=plain_text)
e.grid(row=0, column=1)
l = tk.Label(cctk, text="Enter shift key:", anchor="e")
l.grid(row=1, column=0, sticky="e")
e = tk.Entry(cctk, textvariable=shift_int)
e.grid(row=1, column=1)
b = tk.Button(cctk, text="Encrypt plain text", command=encryption)
b.grid(row=2, columnspan=2)
l = tk.Label(cctk, text="Result:", anchor="e")
l.grid(row=3, column=0, sticky="e")
l = tk.Label(cctk, textvariable=result_text, anchor="w") # place for result
l.grid(row=3, column=1, sticky="w")
b = tk.Button(cctk, text="Exit", command=cctk.destroy)
b.grid(row=4, columnspan=2)
cctk.mainloop()