【问题标题】:Keep window open when execute python script执行python脚本时保持窗口打开
【发布时间】:2021-09-13 04:10:55
【问题描述】:

我正在尝试询问打开文件,获取路径并打开它以进行报告。我的代码如下:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import sys
import os
import openpyxl as xl
import pandas as pd
import numpy as np
        
def get_file():
    global file_abc
    file_abc = filedialog.asktoopenfilename(title = "Select A File",filetypes=(("xlsx","*xlsx),("All Files,"*.*)))
    
window = tk.TK()
window.title("Get File")
window.geometry('1000x1000')
    
button1 = tk.Button(window,text="File_ABC",command=get_file,bg='#6eb5ff',fg'white',width=100).pack()
button2 = tk.Button(window,text="Run",command=window.destroy,bg='#b28dff',fg'white',width=100).pack()
window.mainloop()

print(file_abc)
abc = pd.read_excel("r'" and file_abc,engine="openpyxl")

但问题是我必须使用window destroy 来运行printread_excel 脚本。我想问有没有另一种方法可以在执行脚本时保持窗口打开。

谢谢和最好的问候。

【问题讨论】:

  • 为什么不把mainloop()后面的两行放在get_file()里面?
  • 还有很多拼写错误。
  • @acw1668 感谢您的回复,我不是编码员,我只想找到一种方法来处理数据而不是 VBA。所以你的意思是我必须这样做:def get_file(): global file_abc file_abc = filedialog.asktoopenfilename(title = "Select A File",filetypes=(("xlsx","*xlsx),("All Files,"*.*))) print(file_abc) abc = pd.read_excel("r'" and file_abc,engine="openpyxl")
  • 基本上是的。但我认为您还需要将abc 声明为全局,否则无法在函数外部访问它。但首先你需要先修复那些拼写错误。
  • @acw1668 是的,这只是一个示例代码。我尝试按照您的建议修复我的代码,但我仍然必须关闭 Tk 窗口才能运行代码。

标签: python pandas tkinter


【解决方案1】:

试试这个

在不同的线程中使用 excel 命令。这可能会有所帮助。

import threading

def your_excel_function(word):
    print(word)

x = threading.Thread(target=your_excel_function, args=("Hello World"))
x.start()

更好的是,将其作为后台守护程序运行。守护进程是后台进程

import threading

def your_excel_function(word):
    print(word)

x = threading.Thread(target=your_excel_function, args=("Hello World"), daemon=True)
x.start()

【讨论】:

  • 感谢您的回复,可以用解释一下或者用我的案例做代码吗?