from tkinter import Tk,simpledialog,messagebox
def read_from_file():
with open('国家、首都名.txt')as file:
for line in file:
line=line.rstrip('\n')
country,city=line.rstrip('/')
the_world[country]=city
def write_to_file(country_name,city_name):
with open('国家、首都名.txt','a') as file:
file.write('\n'+country_name+'/'+city_name)
print('咨询专家 - 世界首都')
root=Tk()
root.withdraw()
the_world={}
read_from_file()
while True:
query_country=simpledialog.askstring('国家','输入国家名称:')
if query_country in the_world:
result=the_world[query_country]
messagebox.showinfo('回答','查询'+query_country+'的首都是'+result+'!')
else:
new_city=simpledialog.askstring('教我','我不知道!'+query_country+'的首都是哪里'+'?')
the_world[query_country]=new_city
write_to_file(query_country,new_city)
root.mainloop()
运行代码结果:
咨询专家 - 世界首都
Traceback (most recent call last):
File "D:\方嘉铭 编程\请教专家.py", line 15, in <module>
read_from_file()
File "D:\方嘉铭 编程\请教专家.py", line 4, in read_from_file
for line in file:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 15: illegal multibyte sequence