从cmd运行脚本时,tkFileDialog不会打开gui

时间:2013-12-28 23:58:34

标签: python user-interface file-io cmd

我建立了一个可以发送文件的信使。我添加了这一行以防止显示tk窗口:

Tk().withdraw()

我用这个命令打开文件

tkFileDialog.askopenfilename()

通过IDLE python编辑器它似乎都工作,但是当我通过cmd打开python脚本并尝试发送文件时,gui根本不显示,并且选择文件的对话框无法打开。 / p>

当我删除命令Tk()。withdraw()时,它似乎再次起作用,但是这个愚蠢的空白Tk窗口仍然显示出来。

如何在不使选择文件对话框消失的情况下从cmd运行脚本时阻止显示空白Tk?

这是代码(我使用的是python 2.7,这不是整个代码,我只粘贴了必要的部分):

from Tkinter import Tk
import tkFileDialog

messege = raw_input()
if messege == "SEND":
    print "Starting to send file..."
    isSendingFile = True
    resDir = tkFileDialog.askopenfilename()
    filetype = resDir[(resDir.rfind('.')):]
    filename = resDir[(resDir.rfind('/') + 1):-(len(filetype))]
    s.send("SEND|name:" + filename + "|type:" + filetype)
    fileToSend = open(resDir, "rb")
    messege = fileToSend.read()
    s.send(messege)
    fileToSend.close()
    isSendingFile = False

1 个答案:

答案 0 :(得分:0)

您可以尝试保留对主窗口的引用:

import os

try: # Python 2
    from Tkinter import Tk
    from tkSimpleDialog import askstring
    from tkFileDialog import askopenfilename
except ImportError: # Python 3
    from tkinter import Tk
    from tkinter.simpledialog import askstring
    from tkinter.filedialog import askopenfilename

root = Tk()
root.withdraw() # hide main window

message = askstring("Message", "What is the message?")
if message == "SEND":
   resdir = askopenfilename()
   root.destroy() # done with gui
   path, filetype = os.path.splitext(resdir)
   filename = os.path.basename(path)
相关问题