我收到类型错误:使用 tkinter 时只能将 str(而不是"NoneType")连接到 str,请告诉我如何解决这个问题



我正在创建一个可以对消息进行加密的程序,但在尝试使用tkinter向其中添加GUI时,我遇到了以下错误:TypeError:只能将str(而不是"NoneType"(连接到str代码如下所示。请告诉我该怎么修。

from tkinter import *
key2 = {
"G": "A",
"H": "B",
"I": "C",
"J": "D",
"K": "E",
"L": "F",
"M": "G",
"N": "H",
"O": "I",
"P": "J",
"Q": "K",
"R": "L",
"S": "M",
"T": "N",
"U": "O",
"V": "P",
"W": "Q",
"X": "R",
"Y": "S",
"Z": "T",
"A": "U",
"B": "V",
"C": "W",
"D": "X",
"E": "Y",
"F": "Z",
" ": " ",
"5": "1",
"6": "2",
"7": "3",
"8": "4",
"9": "5",
"0": "6",
"1": "7",
"2": "8",
"3": "9",
"4": "9"
}
key = {
"A": "G",
"B": "H",
"C": "I",
"D": "J",
"E": "K",
"F": "L",
"G": "M",
"H": "N",
"I": "O",
"J": "P",
"K": "Q",
"L": "R",
"M": "S",
"N": "T",
"O": "U",
"P": "V",
"Q": "W",
"R": "X",
"S": "Y",
"T": "Z",
"U": "A",
"V": "B",
"W": "C",
"X": "D",
"Y": "E",
"Z": "F",
" ": " ",
"1": "5",
"2": "6",
"3": "7",
"4": "8",
"5": "9",
"6": "0",
"7": "1",
"8": "2",
"9": "3",
"0": "4"
}
root = Tk()
root.geometry("300x670")
root.minsize(300, 670)
root.maxsize(670, 300)
output = " "
def zero_or_one():
def incase_0():
output = ""
for ch in e1.get():
output += key.get(ch)
l1 = Label(root, text=output, width=49)
l1.grid(column=0)
def incase_1():
output= ""
for ch in e1.get():
output += key2.get(ch)
l1 = Label(root, text=output, width=49)
l1.grid(column=0)
if e.get() == '0':
e1 = Entry(root, width=49)
e1.grid(column=0)
but = Button(root, text="god damn it", command=incase_0)
but.grid(column=0)
elif e.get() == '1':
e1 = Entry(root, width=49)
e1.grid(column=0)
but = Button(root, text="god damn it", command=incase_1)
but.grid(column=0)
elif e.get() == "quit":
exit()
elif e.get() == 'help':
txt = '''
press 0 to cipher a message
press 1 to decipher a message 
type help to get instructions
type quit to close program'''
l1 = Label(root, text=txt, width=49)
l1.grid(column=0)

e = Entry(root, width=49)
e.grid(column=0)
b = Button(root, text="press", command=zero_or_one)
b.grid(row=1, column=0)


root.mainloop()

很抱歉,如果代码有任何缩进问题,SO没有正确缩进

首先,让我向您解释错误。错误倾向于说您正在将字符串与None连接(或组合(,这是不可能的。因此,为了找到修复方法,您必须识别代码中发生错误的部分。

因此,通过我的分析,我发现了字符串串联的两个地方,并且由于Python是一种解释器语言,正如@Thierry Lathuille所建议的那样,完整的错误回溯对求解器来说是最有信息和好处的。

output = ""
for ch in e1.get():
output += key.get(ch)
output = ""
for ch in e1.get():
output += key2.get(ch)

我相信您正在使用tkinter的Entry小部件。上面的内容很容易出现大量的错误和错误,就好像有人在你的字典keykey2中键入了一个特殊的字符或未包含的字符作为key一样,字典的get()函数会返回None

那么,如何修复呢?正如你所想的,这很简单。有多种方法可以稍微简化您的代码,但我将留给您考虑。对于解决方案,您可以添加一个if来检查key是否存在。

output = ""
for ch in e1.get():
if ch in key: # Returns True if the key exists, otherwise False
output += key.get(ch)

相关内容

最新更新