简体   繁体   中英

Python webbrowser.open line opens two tabs when it is not supposed to

Below I have the following code which opens the correct URL after opening an incorrect one. I know that the link is not getting generated twice because of the print(link) output. So one link is somehow opening two tabs on my browser and I have no idea why. Any thoughts would be appreciated!

I am running python 3.6 on windows 10.

from PIL import Image, ImageEnhance, ImageFilter
import pyscreenshot as ImageGrab
import pytesseract
import webbrowser
import urllib

# I have other code in the middle that is not important

query = textQ
query_encoded = urllib.parse.quote_plus(query)
link = 'http://google.com/search?q='+ query_encoded
print(link)
webbrowser.open_new_tab(link)

EDIT 1 why does this code below open two tabs?

from PIL import Image, ImageEnhance, ImageFilter
import pyscreenshot as ImageGrab
import pytesseract
import webbrowser
import urllib


pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-
OCR/tesseract'


if __name__ == "__main__":
    # part of the screen
    img=ImageGrab.grab()
    img.save('screenshot.png')
#-#


query = "textQ"
query_encoded = urllib.parse.quote_plus(query)
link = 'http://google.com/search?q='+ query_encoded
print(link)
webbrowser.open_new_tab(link)

I came across the same issue, when trying to make links clickable in a text editor. I am using Python 2.7.13 on Windows 10, using gtk in the text editor, and I found events handling to be the cause of my problem.

I suspect your other 'unimportant code' might be causing problems, as I could not reproduce the error with code you put in your question. I don't know if my problem/solution is applicable but I hope it helps:

Problem Identification: The text editor I'm working on detects changes in the text buffer and autosaves. When autosaving it connects a button-press signal to a hyperlink_clicked_handler. So my problem was that a new connection to the handler was done whenever it autosaves (when I edit text). From then on, clicking on a link activates signal handling in multiple handlers, which opens the url in a new tab each, hence opening multiple tabs.

Solution: Check if the handler is already connected before connecting handler, so that only one handler is connected.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM