當我單擊“測驗”按鈕時,我試圖一次打開一個 URL(按文本檔案中的順序)。我的代碼所做的是奇怪地一個接一個地反復打開所有 URL。
文本檔案:
https://google.com
https://yahoo.com
https://facebook.com
https://youtube.com
這是代碼:
import tkinter as tk
from random import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from time import *
root = tk.Tk()
app_width = 1000
app_height = 620
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)
root.geometry(f'{app_width}x{app_height} {int(x)} {int(y)}')
PATH ="C:\Program Files (x86)\chromedriver.exe"
testbtn_txt = tk.StringVar()
testbtn = tk.Button(root, textvariable=testbtn_txt, command=lambda:testfunc(), font="Arial", bg="#808080", fg="white", height=1, width=10)
testbtn_txt.set("Test")
testbtn.grid(row=10, column=0, columnspan=2, pady=5, padx=5)
def testfunc():
global driver
driver = webdriver.Chrome(PATH)
sleep(5)
f = open("updatedlist.txt")
urls = [url.strip() for url in f.readlines()]
for url in urls:
driver.get(url)
return driver
root.mainloop()
我究竟做錯了什么?
uj5u.com熱心網友回復:
首先,您將 URL 讀入一個串列并將該串列轉換為迭代器。這允許簡單地用于next獲取下一個 URL。因此,按下按鈕將簡單地打開nextURL,如果沒有更多要打開的內容,它將停止進一步執行該功能:
import tkinter as tk
from selenium import webdriver
PATH ="C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
with open('myfile.txt') as file:
urls = iter([line.strip() for line in file])
def open_next():
try:
driver.get(next(urls))
except StopIteration:
print('no more urls')
return
root = tk.Tk()
btn = tk.Button(root, text='Open next url', command=open_next)
btn.pack(padx=10, pady=10)
root.mainloop()
其他幾件事:
您不需要使用.readlines,最好使用with(背景關系管理器)打開檔案。如果函式不帶引數lambda,command則不需要使用in 。也不要使用time,它在這個架構中沒有位置,因為它凍結了整個執行緒和行程,而且你很少希望 GUI 發生這種情況。也Variable為S這樣的StringVars的不是真正需要的ButtonS,只是用自己的text說法,如果你需要,要改變使用config。
另外:
我強烈建議*在匯入某些內容時不要使用通配符 ( ),您應該匯入您需要的內容,例如from module import Class1, func_1, var_2等等或匯入整個模塊:import module然后您也可以使用別名:import module as md或類似的東西,重點是不要除非您確實知道自己在做什么,否則不要匯入所有內容;名稱沖突是問題所在。
uj5u.com熱心網友回復:
您的問題是由于您在for回圈中直接并立即打開網址造成的
f = open("updatedlist.txt")
urls = [url.strip() for url in f.readlines()]
for url in urls:
driver.get(url)
我不熟悉tkinter所以我不能說你的代碼應該是怎樣的,但邏輯應該如下:
f = open("updatedlist.txt")
urls = [url.strip() for url in f.readlines()]
for url in urls:
#here create a button based on the current url and click it
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/385735.html
上一篇:如何從文本小部件中洗掉大括號
