我是编程新手和 python 新手。我刚刚开发了我的第一个脚本,它处理文件,但目前只能从命令行。
这对我来说只是一种爱好,所以我的工作并不依赖它:-)
我花了几天时间试图了解python gui开发并得出结论,我一定是愚蠢的。
我看过 wxpython & Tkinter & 也不明白,尽管 Tkinter 似乎是两者中更容易的。我什至看过像 Boa Contrictor 和 wxglade 这样的所见即所得工具。我什至不明白如何使用这些。无论如何,我宁愿手动坚持使用我的编辑器和代码。
我的问题是这样的:
我想创建一个包含 1 个或两个对象的桌面窗口,具体取决于最适合的对象。如果只有一个对象,则为某种文本框,如果为 2 个对象,则为文本框和图像。
我希望能够从文件管理器中拖动文件并将它们放在我的脚本窗口中,这只是为了将文件名传递给我的脚本。
我不想将标准输出重定向到我的桌面窗口中的一个对象,以便所有脚本输出都出现在桌面窗口中。
我不确定一个对象是否可以同时做这两件事。如果可以,那么仅一个文本框就足够了,否则将文件拖放到图像上并将输出重定向到文本框。
我在网上找到了拖放示例,但没有任何包含标准输出重定向的示例,并且我无法成功修改我遇到的任何示例。
如果某个善良的鞋底有时间展示如何实现我想要的并解释它的工作原理,我将不胜感激!
- - 编辑 - -
我一直在玩 2 个示例,并设法将 2 个示例混在一起,以获得我想要的工作。代码如下。它尚未清理(旧评论等......),但它有效。
#!/usr/bin/python
# The next two lines are not necessary if you installed TkDnd
# in a proper place.
import os
from Tkinter import *
os.environ['TKDND_LIBRARY'] = '/home/clinton/Python/tkdnd2.6/'
import Tkinter
from untested_tkdnd_wrapper import TkDND
class Redir(object):
# This is what we're using for the redirect, it needs a text box
def __init__(self, textbox):
self.textbox = textbox
self.textbox.config(state=NORMAL)
self.fileno = sys.stdout.fileno
def write(self, message):
# When you set this up as redirect it needs a write method as the
# stdin/out will be looking to write to somewhere!
self.textbox.insert(END, str(message))
root = Tkinter.Tk()
dnd = TkDND(root)
textbox = Tkinter.Text()
textbox.pack()
def handle(event):
event.widget.insert(END, event.data)
content = textbox.get("0.0",Tkinter.END)
filename = content.split()
dnd.bindtarget(textbox, handle, 'text/uri-list')
#Set up the redirect
stdre = Redir(textbox)
# Redirect stdout, stdout is where the standard messages are ouput
sys.stdout = stdre
# Redirect stderr, stderr is where the errors are printed too!
sys.stderr = stdre
# Print hello so we can see the redirect is working!
print "hello"
# Start the application mainloop
root.mainloop()
示例是:python 将资源管理器文件拖放到 tkinter 条目小部件
还有 Noelkd 提供的示例。
为了使此代码正常工作,您必须从第一个示例创建包装器。目前代码也只是在窗口中显示拖动的文件,但是变量已经到位,可以传递给在 gui 界面后面运行的脚本。