fork(2) download
  1. import re
  2. from tkinter import *
  3. from tkinter.filedialog import *
  4. from tkinter.messagebox import *
  5. from random import randint
  6. import pickle
  7. import time
  8.  
  9. class Dict():
  10. def __init__(self):
  11. self.mydict = {}
  12. self.currentdict = []
  13. self.current_word = ''
  14. self.current_answer = []
  15. self.life = 0
  16. self.start_time = 0
  17. self.finish_time = 0
  18. self.my_time = 0
  19.  
  20. def add_item(self,event, enword,ruwords,entry1,entry2):
  21. en = enword.strip()
  22. if re.match(r'\b[a-z]+\b', enword) and re.match(r'^([А-Яа-я]+\s*,{1}\s*)+([А-Яа-яё]+){1}$|^[А-Яа-яё]+$',ruwords):
  23. ru = [i.strip() for i in ruwords.split(',')]
  24. it = {en : ru}
  25. self.mydict.update(it)
  26. entry1.delete(0,END)
  27. entry2.delete(0,END)
  28.  
  29. def save_dict(self):
  30. name = asksaveasfilename()
  31. f = open(name, 'wb')
  32. pickle.dump(self.mydict,f)
  33. self.mydict = {}
  34. f.close()
  35.  
  36. def open_dict(self):
  37. try:
  38. name = askopenfilename()
  39. f = open(name,'rb')
  40. self.mydict = pickle.load(f)
  41. self.currentdict = [i for i in self.mydict]
  42. self.life = round(len(self.mydict) * 0.25)+1
  43. if mtime.get() == 0:
  44. self.my_time = len(self.mydict) * 9000
  45. else:
  46. self.my_time = len(self.mydict) * mtime.get()
  47. f.close()
  48. except: pass
  49.  
  50. def get_answer(self,event):
  51. self.current_answer = ruword.get()
  52. if len(self.current_answer) == 0:
  53. pass
  54. else:
  55. try:
  56. right_answer = self.mydict.get(self.current_word)
  57. if self.current_answer in right_answer:
  58. showrighta.configure(text='')
  59. showrightb.configure(text='')
  60. ruword.delete(0,END)
  61. result.configure(text= 'Верно',fg='green')
  62. word = self.currentdict.pop(randint(0,len(self.currentdict)-1))
  63. self.current_word = word
  64. enword.delete(0,END)
  65. enword.insert(END,word)
  66. else:
  67. self.life-=1
  68. ruword.delete(0,END)
  69. result.configure(text= 'Неправильно.',fg='red')
  70. showrighta.configure(text='Возможные варианты: ')
  71. showrightb.configure(text= ', '.join(self.mydict.get(self.current_word)).strip(', '))
  72. word = self.currentdict.pop(randint(0,len(self.currentdict)-1))
  73. self.current_word = word
  74. enword.delete(0,END)
  75. enword.insert(END,word)
  76. except ValueError:
  77. self.finish_time = round(time.time())
  78. ruword.delete(0,END)
  79. ruword.insert(END, 'Конец словаря')
  80. if self.life > 0 and self.my_time - (self.finish_time - self.start_time) > 0:
  81. finaltext.configure(text= 'Отлично! Словарь успешно закреплён.',fg='gold',bg='gray')
  82. else:
  83. finaltext.configure(text= 'Вы недостаточно хорошо знаете эти слова.\n Попробуйте снова в другой раз.',fg='blue',bg='red')
  84. bstudy.configure(state='normal')
  85. result.configure(text='')
  86. showrighta.configure(text='')
  87. showrightb.configure(text='')
  88.  
  89. def start(self):
  90. finaltext.configure(text= '')
  91. if len(self.currentdict) < 1:
  92. self.currentdict = [i for i in self.mydict]
  93. word = self.currentdict.pop(randint(0,len(self.currentdict)-1))
  94. self.current_word = word
  95. ruword.delete(0,END)
  96. enword.delete(0,END)
  97. enword.insert(END,word)
  98. bstudy.configure(state='disabled')
  99. self.start_time = round(time.time())
  100.  
  101. def restart(self):
  102. self.start_time = 0
  103. self.finish_time = 0
  104. self.currentdict = [i for i in self.mydict]
  105. self.life = round(len(self.mydict) * 0.25)+1
  106. self.start()
  107.  
  108. def create_new(self):
  109. self.mydict = {}
  110. newin = Toplevel(mywin)
  111. newin.title('Создание словаря')
  112. newin.geometry('600x240')
  113. newin.resizable(0,0)
  114. enterenword = Entry(newin,width=36)
  115. enterruswords = Entry(newin,width=36)
  116. en = Label(newin,text = 'English word:\n (for example: "script")',font=12)
  117. ru = Label(newin, text = 'Русский(е) эквивалент(ы):\n (например: "сценарий, почерк,\nподлинник")', font = 12)
  118. enterruswords.bind('<Return>', lambda event='<Return>' : self.add_item('<Return>', enterenword.get(), enterruswords.get(),enterenword,enterruswords))
  119. en.place(x=5,y=10)
  120. enterenword.place(x=255,y=10)
  121. ru.place(x=5,y=60)
  122. enterruswords.place(x=255,y=60)
  123. saveme = Button(newin,text='Сохранить',bg='#9ACEEB',height=4,width=25,command=d.save_dict)
  124. add_it = Button(newin,text='Добавить',bg='#9ACEEB',height=2,width=8, command= lambda event='<Button-1>' : self.add_item('<Button-1>', enterenword.get(), enterruswords.get(),enterenword,enterruswords))
  125. add_it.place(x=500,y=50)
  126. saveme.place(x=200,y=160)
  127.  
  128. def myhelp():
  129. showinfo(title='qwertyнекуцй',
  130. message='''Кнопка "Повторить" позволяет ПОВТОРНО упражняться с одним и тем же словарём.\n
  131. Открыв новый словарь, используйте кнопку "Go!"\n
  132. Указав кол-во секунд, вы ограничите допустимое время тренировки кол-вом секунд, умноженным на кол-во слов в вашем словаре\n
  133. Создавая словарь, вводите слова без кавычек, разделяя русские эквиваленты английского слова запятыми.\n
  134. Добавляйте каждую новую позицию в словарь, испольуя кнопку "Добавить", после чего сохраните файл.''')
  135. d = Dict()
  136. #
  137. mywin = Tk()
  138. mywin.resizable(0,0)
  139. mywin.geometry('900x450')
  140. mywin.title('en-ru trainer')
  141. mtime = IntVar()
  142. chtime = [2,4,6,8,10]
  143. choosetime = OptionMenu(mywin, mtime, *chtime)
  144. result = Label(mywin,text='',font = 16)
  145. showrighta = Label(mywin, text='',font=14, fg='orange')
  146. showrightb = Label(mywin, text='',font=16, fg='green')
  147.  
  148. timetext = Label(text='Тренировка на время выключена\n(включить, указав кол-во секунд)')
  149. enword = Entry(mywin,width=40)
  150. ruword = Entry(mywin,width=40)
  151. bstudy = Button(mywin,text='Go!',command = d.start,height=5,width=12,bg='#ED760E',fg='white',font=18)
  152. bopenfile = Button(text='Открыть словарь...', command= d.open_dict,height=4,width=16,bg='#9ACEEB')
  153. bcreatenewdict = Button(text='Создать новый словарь...',command= d.create_new,bg='#9ACEEB')
  154. restart = Button(text='Повторить', command=d.restart,height=4,width=16,bg='#9ACEEB')
  155. ruword.bind('<Return>',d.get_answer)
  156. finaltext = Label(text='',font = 14)
  157. enblahblah = Label(text='Английское слово: ',font=14)
  158. rublahblah = Label(text='Перевод: ',font=14)
  159. mymenu = Menu(mywin)
  160. mywin.config(menu=mymenu)
  161. mmain = Menu(mymenu)
  162. mymenu.add_cascade(label='Справка',menu=mmain)
  163. mmain.add_command(label='Help', command=Dict.myhelp)
  164. enblahblah.place(x=12,y=100)
  165. rublahblah.place(x=12,y=150)
  166. enword.place(x=200,y=100)
  167. ruword.place(x=200,y=150)
  168. bstudy.place(x=365,y=200)
  169. bopenfile.place(x=700,y=50)
  170. restart.place(x=700,y=160)
  171. timetext.place(x=680,y=270)
  172. choosetime.place(x=755,y=310)
  173. result.place(x=300,y=35)
  174. showrighta.place(x=80,y=70)
  175. showrightb.place(x= 250,y=70)
  176. finaltext.place(x=110, y=330)
  177. bcreatenewdict.place(x=30,y=388)
  178. #
  179. mywin = mainloop()
  180.  
Runtime error #stdin #stdout #stderr 0.06s 29056KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 137, in <module>
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1854, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable