我正在编写一个简单的程序,基本上可以发出随机单词。 但事情发生了。
AttributeError: 'int' object has no attribute 'encode'
这是程序。
from tkinter import *
import random,os,sys,shelve,pickle
def atoi(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
class Application(Frame):
"a application baced GUI"
def __init__(self,master):
"to initilize the frame"
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.bttn_to_sumbit = Button(self,text = "SHOOT!",command = self.shoot)
self.bttn_to_sumbit.grid(row = 4,column = 5,sticky = E)
self.ins = Text(self, width = 30, height = 20, wrap = WORD)
self.ins.grid(row = 11, column = 1, sticky = E)
self.ins.delete(0.0,END)
self.ins.insert(0.0,"Your words will be displayed here")
def shoot(self):
try:
fd = open("CurrentNum.txt","r")
except FileNotFoundError:
self.ins.delete(0.0,END)
self.ins.insert(0.0,"NO WORDS FIND!!")
f = shelve.open("Data.dat")
num = fd.read()
rnum = len(num)
nnum = str(rnum)
tnums = atoi(nnum)
key = random.randint(1,tnums)
print(key)
self.next = Button(self,text = "Next",command = self.shoot)
word = f[key]
self.ins.delete(0.0,END)
self.ins.insert(0.0,word)
root = Tk()
root.title("WordShooter BETA")
root.geometry("500x150")
app = Application(root)
root.mainloop()
耶。如果您有任何建议,请回复。 如果你想要我的杰作。转到goo.gl/c7yxBL> scc>密码:SCCdatabase 感谢
答案 0 :(得分:4)
f
是shelve
对象(类似字典的结构)。 key
是一个整数。然后,您尝试在key
中查找f
,但是,根据documentation on shelve
:
键是普通字符串。
首先将key
投射到字符串。
key = str(random.randint(1,tnums))