#python #tkinter #eof #easygui
#python #tkinter #eof #easygui
Вопрос:
Следующий код выдает мне эту ошибку «Ошибка токена: EOF в многострочном операторе». Что это за ошибка? Как я могу это исправить?
import easygui
import time
namegui = easygui.enterbox(msg='Enter your name:', title='Name query', default='Gian')
situationgui = easygui.enterbox(msg='Please enter your situation:', title='Thought Log(Situation)')
thoughtsgui = easygui.enterbox(msg='Please enter your thoughts:', title='Thought Log(Thoughts')
emotionsgui = easygui.enterbox(msg='Please enter your emotions: n Sad, Mad, Hurt, Depressed, Anxious, Tense, etc.', title='Thought Log(Emotions')
behaviorgui = easygui.enterbox(msg='Please enter your behavior:', title='Thought Log(Behavior')
thinking_trapsgui = easygui.enterbox(msg='Please identify your thinking traps: n n'
'FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! n n'
'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! n n'
'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! n n'
'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. n n'
'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. n n'
'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. n n'
'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account n n',
title='Thought Log(Identify Your Thinking Traps)')
BAI_var = easygui.choicebox(
msg='Please identify your thinking traps: n n',
title='Thought Log(Identify Your Thinking Traps)',
choices=('FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! n n
'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! n n'
'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! n n'
'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. n n'
'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. n n'
'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. n n'
'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account n n')
alt_behaviorgui = easygui.enterbox(msg='Please enter alternative behavior:', title='Thought Log(Alt Behavior)')
alt_thoughtsgui = easygui.enterbox(msg='Please enter alternative thoughts:', title='Thought Log(Alt Thoughts)')
yeargui = easygui.enterbox(msg='Enter the current year:', title='Current Year', default='2011')
monthgui = easygui.enterbox(msg='Enter the current month:', title='Current Month')
daygui = easygui.enterbox(msg='Enter the current day:', title='Current Day')
time_hourgui = easygui.enterbox(msg='Enter the current hour:', title='Current Hour')
time_minutegui = easygui.enterbox(msg='Please enter current minutes:', title='Current Minute')
am_pmgui = easygui.enterbox(msg='Please enter either am or pm:', title='AM OR PM')
file = open('Thought Record 1.0.txt', 'a')
file.write(namegui 'n')
file.write(daygui)
file.write('/')
file.write(monthgui)
file.write('/')
file.write(yeargui)
file.write('n')
file.write('Your situation:')
file.write(situationgui)
file.write('n')
file.write('Your thoughts:')
file.write(thoughtsgui)
file.write('n')
file.write('Your emotions:')
file.write(emotionsgui)
file.write('n')
file.write('Your behavior:')
file.write(behaviorgui)
file.write('n')
file.write('Thinking traps:')
file.write(thinking_trapsgui)
file.write('n')
file.write('Alternative bahvior:')
file.write(alt_behaviorgui)
file.write('n')
file.write('Alternative thoughts:')
file.write(alt_thoughtsgui)
file.write('n')
file.write('n')
file.close()
Эта ошибка появилась только после того, как я добавил следующие строки кода.
BAI_var = easygui.choicebox(
msg='Please identify your thinking traps: n n',
title='Thought Log(Identify Your Thinking Traps)',
choices=('FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! n n
'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! n n'
'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! n n'
'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. n n'
'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. n n'
'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. n n'
'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account n n')
Я использую Python 2.5 на Mac OS X 10.6
Комментарии:
1. Вот подсказка. Взгляните на свой код выше и обратите особое внимание на цвет синтаксиса. Кто бы мог подумать, что SO можно использовать для отладки пропущенных кавычек? 🙂
Ответ №1:
Ваша первая строка в переменной choices не имеет апострофа ( '
) в конце.
Ответ №2:
Не прямой ответ на исходный вопрос, но поскольку поиск в Интернете привел меня сюда… Я получил эту ошибку по другой причине: случайная скобка! Но это пришло из flake8. Вот фрагмент кода для его воспроизведения:
import socket
def all_good(name):
name_line = f"Name: {name}")
print(name_line)
Я сохранил это в файл с именем error.py . Теперь, если я запущу на нем flake8:
$ flake8 error.py
error.py:1:1: E902 TokenError: EOF in multi-line statement
Что довольно озадачивает, поскольку многострочного оператора нигде нет! В конце концов я обнаружил ошибку, но мораль истории в том, что я бы нашел ее намного быстрее, если бы запустил ее через интерпретатор python:
$ python3 error.py
File "error.py", line 5
name_line = f"Name: {name}")
^
SyntaxError: unmatched ')'
Исправьте это:
import socket
def all_good(name):
name_line = f"Name: {name}"
print(name_line)
И теперь flake8
действительно выполнит свою работу:
$ flake8 error.py
error.py:1:1: F401 'socket' imported but unused
Это очевидно, но помните: сначала проверьте код с python3
помощью, затем запустите его через linters или другие средства проверки.
Комментарии:
1. Спасибо за совет по использованию интерпретатора!
2. Спасибо, это была именно моя проблема. Случайно снял дополнительную закрывающую скобку при переформатировании кода.
3. Ключ к
this
ошибке, по-видимомуflake8
, теряется и сообщает об ошибке как о возникновении в строке: 1 символ: 1, т.е.error.py:1:1: E902 TokenError: EOF in multi-line statement
Ответ №3:
Вам не хватает заключительной цитаты в строке гадания.
Это легко найти, потому что именно здесь подсветка синтаксиса становится другой.
Ответ №4:
Решение: вырежьте один раздел вашего кода и посмотрите, исчезнет ли эта ошибка. Если это так, то проблема заключается в стороне этого раздела, если это не так, найдите другой раздел для вырезания… подсказка: раздел, над которым вы работали последним 🙂
Ответ №5:
После того, как я добавил еще одну закрывающую скобку в конце, ошибка «Ошибка токена: EOF в многострочном операторе» исчезла.
Последняя строка
Перед изменением: «ЧРЕЗМЕРНОЕ ОБОБЩЕНИЕ: это когда мы используем такие слова, как всегда или никогда, для описания ситуаций или событий. Это проблематичный способ мышления, потому что он не учитывает все ситуации или события n n’)
После изменения: «ЧРЕЗМЕРНОЕ ОБОБЩЕНИЕ: это когда мы используем такие слова, как всегда или никогда, для описания ситуаций или событий. Это проблематичный способ мышления, потому что он не учитывает все ситуации или события n n ‘))
Примечание: в конце добавлено еще одно). Я протестировал, и это сработало.