第二次运行python代码时出错

2024-09-28 03:15:24 发布

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

我编写了这段代码来使用python从网站中获取数据。当我第一次运行它时,它运行得非常完美。 在第一次运行时,我从用户处获取许可证。并将其保存在license.dat文件中,以便用户无需在每次使用软件时添加许可证。 但是当我再次运行软件时,它会给出一个错误。 软件正在运行,但在第二次运行时,它会在控制台窗口中显示这一点

can't invoke "event" command: application has been destroyed while executing "event generate $w <>" (procedure "ttk::ThemeChanged" line 6) invoked from within "ttk::ThemeChanged"

这是我的密码:

from bs4 import BeautifulSoup
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import pandas as pd
import requests
import time
from datetime import date
from licensing.models import *
from licensing.methods import Key, Helpers
import pickle
import os


RSAPubKey = "<RSAKeyValue><Modulus>v1Ym5pYBWr0oYBvQkMvm7sp2vxqXKf9zpe0rSfCGBRrJqAh/u6HNgvMNKuhhr9IYCa5dkfWRjK343+hJ6SuQQVdlKx+azG7x2TRz/YPQj/wXBo5UDLCMafShPoRfHPCsvgTnYX8cGQZXDlzYuCRH/1dZAAjlOL1a3oWChZvyZWqiZa8kyxGlFQBSqb2Z1NfKZJXCsAVedDR9uSPbHywFWAVMgkwG+CH+5jwUPl0rpqrnmIL5IHA1hnMIp7FOhc+Nb0hqIIDAedQhCHZwRLDsAp6qwCNq1S+QvonV5e0v+os0wLjc7XSa6v0kCOLI5buUn/7vV7DRoAA+iSYMHC93+w==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
auth = "myauthtoken"

count = 0
today = date.today()
global b1,b2,bar,window,inputtxt,errorlabel
licensewindow=Tk()


def dellicesnse():
    os.remove("license.dat")
    exit()

def start():
    global count, time
    count += 1
    if count >= 2:
        b1.config(state=DISABLED)
        b1.unbind("<Button-1>")
        time = 120
        count = 0

        def countdown():
            global time
            if time >= 0:
                time -= 1
            else:
                global count
                b1.config(state=NORMAL)
                b1.bind("<Button-1>", start)

        countdown()
    else:
        names = []
        opens = []
        highs = []
        lows = []
        closes = []
        i = 0
        r = requests.get(
            "https://www.moneycontrol.com/stocks/marketstats/indexcomp.php?optex=NSE&opttopic=indexcomp&index=9")
        soup = BeautifulSoup(r.text, "html.parser")
        results = soup.find("table", {"class": "tbldata14 bdrtpg"})
        links = results.findAll("td", {"class": "brdrgtgry"})
        # links = results.findAll("a", {"class": "bl_12"})
        # print(links)
        for items in links:
            try:
                item_href = items.find("a").attrs["href"]
                if "optex" in item_href:
                    list.remove(item_href)
                url = "https://www.moneycontrol.com" + item_href
                s = requests.get(url)
                soup = BeautifulSoup(s.text, "html.parser")
                resultss = soup.find("div", {"id": "mc_mainWrapper"})
                nametag = resultss.find("div", {"id": "stockName"})
                name = nametag.find("h1").text
                close = resultss.find("div", {"id": "nsecp"}).text
                low = resultss.find("div", {"id": "sp_low"}).text
                high = resultss.find("div", {"id": "sp_high"}).text
                open = resultss.find("td", {"class": "nseopn bseopn"}).text
                names.append(name)
                opens.append(open)
                highs.append(high)
                lows.append(low)
                closes.append(close)
                i += 2
                time.sleep(0.05)
                bar['value'] += i
                window.update_idletasks()

            except:
                pass

        d4 = today.strftime("%B %d, %Y")
        df = pd.DataFrame({'Name': names, 'Open': opens, 'High': highs, 'Low': lows, 'Close': closes})
        df.to_csv('Nifty 50 Data '+d4+'.csv', index=False, encoding='utf-8')
        if i == 100:
            messagebox.showinfo('Nifty 50 Stocks Data', 'Data Extracted Successfully')


def exit1():
    exit()


global inp


def AuthKey():
    try:
        key=pickle.load(open("license.dat", 'rb'))
    except (OSError, IOError) as e:
        key = inputtxt.get(1.0, "end-1c")
        pickle.dump(key, open("license.dat", 'wb'))
    result = Key.activate(token=auth,
                          rsa_pub_key=RSAPubKey,
                          product_id=12568,
                          key=key,
                          machine_code=Helpers.GetMachineCode())

    if result[0] == None or not Helpers.IsOnRightMachine(result[0]):
        errorlabel.config(text="ERROR: {0}".format(result[1]))
        if os.path.isfile("license.dat"):
            os.remove("license.dat")

    else:
        licensewindow.destroy()
        window = Tk()
        window.geometry("400x160")
        window.minsize(400, 160)
        window.maxsize(400, 160)
        window.title("Nifty Large Cap.")
        tabControl = Notebook(window)
        tab1 = Frame(tabControl)
        tab2 = Frame(tabControl)
        tab3 = Frame(tabControl)
        tabControl.add(tab1, text='Home')
        tabControl.add(tab2, text='License')
        tabControl.add(tab3, text='About')
        tabControl.pack(expand=1, fill="both")

        label1 = Label(tab1, text="Nifty Large Cap.", font=("arial", 20, "bold")).pack()
        bar = Progressbar(tab1, orient=HORIZONTAL, length=200)
        bar.place(x=100, y=50)
        b1 = Button(tab1, text="Start", width=12, command=start).place(x=90, y=90)
        b2 = Button(tab1, text="Exit", width=12, command=exit1).place(x=225, y=90)
        label2=Label(tab1, text="Note: To Get Correct Market Data Run Application After 4:00 PM.", font=("arial", 8, "italic")).place(x=50, y=120)

        tab2l1= Label(tab2, text="Your Key: "+pickle.load(open("license.dat", 'rb')), font=("arial", 10, "italic")).pack()
        dellicensebtn= Button(tab2, text="Delete License File", width=20, command=dellicesnse).pack()

        about1 = Label(tab3, text="Nifty Large Cap. The software is designed to get data from Nifty 50", font=("arial", 10, "italic"))
        about1.pack()
        about2 = Label(tab3, text="on a daily basis. It will give you 50 companies Open, High, Low &", font=("arial", 10, "italic"))
        about2.pack()
        about3 = Label(tab3, text="Close Price with the stock names in Excel File.",font=("arial", 10, "italic"))
        about3.pack()
        



        window.mainloop()

        pass


if os.path.isfile("license.dat"):
    AuthKey()

licensewindow.geometry("400x100")
licensewindow.minsize(400, 100)
licensewindow.maxsize(400, 100)
licensewindow.title("License")
licenselabel = Label(licensewindow, text="Key: ", font=("arial", 10, "bold")).place(x=10, y=20)
inputtxt = Text(licensewindow, height=1, width=40)
inputtxt.place(x=55, y=20)
submitButton = Button(licensewindow, text="Submit", command=AuthKey).place(x=150, y=55)
errorlabel = Label(licensewindow, text="", font=("arial", 8))
errorlabel.place(x=10, y=80)
licensewindow.mainloop()

此外,这是我在第二次运行exe后收到的错误 Error Image


Tags: textfromimportiftimelicenseplacefind

热门问题