如何在Python中而不是在IDLE中打开文件、web浏览器和url。

2024-10-01 13:44:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道你可以在pythongui中打开文件、浏览器和url。但是,我不知道如何将此应用到程序中。例如,下面这些都不起作用。(以下是我成长中的聊天机器人程序的片段):

def browser():
    print('OPENING FIREFOX...')
    handle = webbroswer.get() # webbrowser is imported at the top of the file
    handle.open('http://youtube.com')
    handle.open_new_tab('http://google.com') 

以及

^{pr2}$

这些错误按照上述顺序发生,但在个别运行中:

OPENING FIREFOX...
Traceback (most recent call last):
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
    askForQuestions()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 64, in askForQuestions
    browser()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 38, in browser
    handle = webbroswer.get()
NameError: global name 'webbroswer' is not defined
>>> 

ENTER THE FILE'S NAME AND EXTENSION:file.txt
Traceback (most recent call last):
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
    askForQuestions()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 66, in askForQuestions
    file()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 51, in file
    action = open(file, 'r')
IOError: [Errno 2] No such file or directory: 'file.txt'
>>> 

我是不是处理错了,或者我可以不在程序中使用open()和webbrowser?在


Tags: inpylinefilesopenusersaifile
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:21

您应该阅读错误并尝试理解它们-在这种情况下它们非常有用-因为它们通常是:

第一个是NameError: global name 'webbroswer' is not defined。 您可以在这里看到,webbrowser在代码中拼写错误。它还告诉您它找到错误的那一行(第38行)

第二个IOError: [Errno 2] No such file or directory: 'file.txt'告诉你你试图打开一个不存在的文件。这不起作用,因为您指定了

    action = open(file, 'r')

也就是说你正在尝试读取一个文件。Python不允许读取不存在的文件。在

相关问题 更多 >