一次运行后,Tkinter窗口自动关闭

如何解决一次运行后,Tkinter窗口自动关闭

因此,我正在编写一个界面,该界面将自动执行一些步骤“数据分析”。该代码涉及将用于不同功能的多个屏幕。我写的第一个是EDA(探索性数据分析)屏幕。该代码有效,但是将生成报告,然后仅关闭Tk窗口。

具体来说,当我生成报告时,代码将生成报告,然后关闭。我没有将代码生成放入其中,因为它不使用Tkinter。还没有列出其他屏幕,因为它们没有问题,我也不想将整个项目转储到这里。

import HTMLCreator as sv
from tkinter import *
import tkinter.filedialog
import time
import pandas as pd
import Credentials as cred
import os
class EDAScreen(Page):
   
    def __init__(self,*args,**kwargs):

        Page.__init__(self,**kwargs)
        self.fields = ['First X Column Name','Last X Column Name','First Y Column name','Last Y Column Name']
        self.entries = []
        self.df=""
        self.things=[]
        self.description = "Automate EDA for a Dataset"
        self.instructions = "Upload the CSV file with all the data"

        self.descriptionLabel = Label(self,text = self.description,font=("System",13)).place(x = 140,y = 150)
        self.instructionsLabel = Label(self,text = self.instructions,13)).place(x = 190,y =180)
        self.genResultButton = Button(self,text = "Upload input file",font=("Arial",18),command = self.open).place(x = 290,y = 230)
        self.edaButton=Button(self,text = "Generate Report",command = self.EDA).place(x = 290,y = 330)
       
        # root.config(background='gray')
        for ndex,field in enumerate(self.fields):
            Label(self,width=20,text=field,anchor='w').grid(row=ndex,column=0,sticky='ew')
            self.entries.append(Entry(self))
            self.entries[-1].grid(row=ndex,column=1,sticky='ew')


        Button(self,text='Set these Params',command=self.fetch).grid(row=len(self.fields)+1,sticky='ew')

    def fetch(self):
        for ndex,entry in enumerate(self.entries):
            print('{}: {}'.format(self.fields[ndex],entry.get()))
            self.things.append(entry.get())
    
    def EDA(self):
        sv.createHTML(self.df,self.things[:2],self.things[2:])

    
    # Get the prediction answer by searching for file
    def open(self):
        filename =  tkinter.filedialog.askopenfilename(parent=self,initialdir = "./",title = "Select file",filetypes = (("data files","*.csv"),("all files","*.*")))
        print(filename)
        self.df=pd.read_csv(filename)
        cols=self.df.columns.values
        print(cols)
        try:  
            os.mkdir("./Breakdowns")
        except :
            pass
        # print("Things: ",things)
       
        #iv.processImg(r,'jpg')

当您没有主循环时,这似乎是一个问题。但是,我确实将其定义为:

if __name__ == "__main__":
    root = Toplevel()
    root.geometry("800x500")
    main = MainView(root)
    main.pack(side="top",fill="both",expand=True)
    root.mainloop()

其他重要定义是

class Page(Frame):

    def __init__(self,**kwargs):
        Frame.__init__(self,**kwargs)

    def show(self):
        self.lift()


class MainView(Frame):

    def __init__(self,**kwargs):
        
        Frame.__init__(self,**kwargs)
        
        introScreen = IntroScreen(self)
        edaScreen = EDAScreen(self)

        buttonFrame = Frame(self)
        container = Frame(self)
        buttonFrame.pack(side="top",fill="x",expand=False)
        container.pack(side="top",expand=True)

        edaScreen.place(in_ = container,x = 0,y = 0,relwidth = 1,relheight = 1)
        introScreen.place(in_ = container,relheight = 1)
        
        introScreenButton = Button(buttonFrame,text = "Go to Intro Screen",command = introScreen.lift,width = 30,height = 2)
        edaScreenButton = Button(buttonFrame,text = "Understand your data in detail",command = edaScreen.lift,height = 2)
        
        edaScreenButton.pack(side = "left")
        introScreenButton.pack(side = "left")
        
        introScreen.show()

class IntroScreen(Page):

    def __init__(self,**kwargs)
        self.backgroundImage = PhotoImage(file = "What is PD.png") 
        #^^ replace with something describing how to use the tool
        backgroundLabel = Label(self,image = self.backgroundImage)
        backgroundLabel.place(x = 0,relheight = 1)

编辑:我的createHTML如下所示。它与Tkinter无关(并且有效)。它在一个名为HTMLCreator的单独文件中。整个文件放在这里。我添加了import语句,以便您可以毫无问题地运行代码。

import pandas as pd
from pandas import Series
# from pygame import mixer # Load the required library
import seaborn as sns
import matplotlib.pyplot as plt
import glob
import sweetviz as sv

def createHTML(df,feature_cols,target_col):
    """
    Create the HTML reports for the dataset given the names
    Params:
    df: dataframe passed,feature_cols: The independent variables (what you input)
    target_col: The dependent vars (what you predict)
    """
    data= df
    ##TODO Set the y_all and target_cols in a way that they get Tk input
    y_all=data.loc[:,target_col[0]:target_col[1]]
    target_col_names = data.loc[:,target_col[0]:target_col[1]].columns.values
    for col in target_col_names:
        X_all = data.loc[:,feature_cols[0]:feature_cols[1]]
        # print(y_all[col])
        X_all[col]=y_all[col]
        # print(X_all[col])
        advert_report=""
        if(len(X_all.columns.values)>50):
            advert_report = sv.analyze(X_all,pairwise_analysis="off",target_feat=col)
        else:
            print("here")
            advert_report = sv.analyze(X_all,pairwise_analysis="on",target_feat=col)

        #display the report
        
        advert_report.show_html('Breakdowns/'+col+'.html')
    
    advert_report = sv.analyze(y_all,pairwise_analysis="on")
        #display the report
        
    advert_report.show_html('Breakdowns/Preds'+'.html')

解决方法

在最初部分生成报告后,我确实遇到了一些问题,但是就我而言,Tk窗口没有关闭。

该错误与HTMLCreator文件中的以下几行有关:

if(len(X_all.columns.values)>50):
    advert_report = sv.analyze(X_all,pairwise_analysis="off",target_feat=col)
else:
    print("here")
    advert_report = sv.analyze(X_all,pairwise_analysis="on",target_feat=col)

Sweetviz目前仅根据文档支持BOOLEAN和NUMERICAL功能作为目标:

target_feat:一个字符串,表示要作为特征的名称 标记为“目标”。只能将BOOLEAN和NUMERICAL特征作为目标 现在。

因此,通过运行以下代码,不会显示错误:

if(len(X_all.columns.values)>50):
    advert_report = sv.analyze(X_all,pairwise_analysis="off")
else:
    print("here")
    advert_report = sv.analyze(X_all,pairwise_analysis="on")

但是,仅将数字列作为target传递仍然会奇怪地引发错误,但是如果列为FeatureConfig对象,则可以使用feature_config = sv.FeatureConfig(force_num=col) if(len(X_all.columns.values)>50): advert_report = sv.analyze(X_all,feat_cfg=feature_config,target_feat=col) 对象作为替代方法来强制数字列的目标不是数字类型,您仍然会收到错误消息。

%%csharp
,

因此,在使用其他EDA工具(例如Pandas Profiling)之后,我已经找到了原因。显然,所有基于Pandas Profiling的程序在完成后(由于某种原因)只是在TKinter下。没有什么可以做的。

,

mainloop()必须遵循被调用的函数(在您的情况下为数据分析)。
例如。

tk = Tk()
tk.title('Data Analysis')
data_analysis_func(args)
tk.mainloop()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res