标签归档:user-interface

使用简单对话框在Python中选择文件

问题:使用简单对话框在Python中选择文件

我想在我的Python控制台应用程序中获取文件路径作为输入。

目前,我只能要求完整路径作为控制台中的输入。

有没有一种触发简单用户界面的方法,用户可以在其中选择文件而不是键入完整路径?

I would like to get file path as input in my Python console application.

Currently I can only ask for full path as an input in the console.

Is there a way to trigger a simple user interface where users can select file instead of typing the full path?


回答 0

使用tkinter怎么样?

from Tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

做完了!

How about using tkinter?

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

Done!


回答 1

Etaoin答案的Python 3.x版本的完整性:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()

Python 3.x version of Etaoin’s answer for completeness:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()

回答 2

使用EasyGui(由pydocepydoc生成的0.96版文档):

import easygui
print(easygui.fileopenbox())

安装:

pip install easygui

演示:

import easygui
easygui.egdemo()

With EasyGui:

import easygui
print(easygui.fileopenbox())

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()

回答 3

在Python 2中,使用tkFileDialog模块。

import tkFileDialog

tkFileDialog.askopenfilename()

在Python 3中,使用tkinter.filedialog模块。

import tkinter.filedialog

tkinter.filedialog.askopenfilename()

In Python 2 use the tkFileDialog module.

import tkFileDialog

tkFileDialog.askopenfilename()

In Python 3 use the tkinter.filedialog module.

import tkinter.filedialog

tkinter.filedialog.askopenfilename()

回答 4

另一个要考虑的选项是Zenity:http://freecode.com/projects/zenity

我遇到的情况是我正在开发Python服务器应用程序(没有GUI组件),因此不想引入对任何python GUI工具包的依赖关系,但是我希望我的一些调试脚本可以通过输入文件进行参数化,并且想要如果用户未在命令行上指定文件,则以可视方式提示用户输入文件。Zenity非常适合。为此,请使用子流程模块调用“ zenity –file-selection”并捕获标准输出。当然,此解决方案不是特定于Python的。

Zenity支持多种平台,并且恰好已经安装在我们的开发服务器上,因此它方便了我们的调试/开发,而没有引入不必要的依赖性。

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn’t want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn’t specify one on the command line. Zenity was a perfect fit. To achieve this, invoke “zenity –file-selection” using the subprocess module and capture the stdout. Of course this solution isn’t Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.


回答 5

我用wxPython获得的结果比tkinter更好,这是对以后重复的问题的回答:

https://stackoverflow.com/a/9319832

wxPython版本通过xfce桌面在我的OpenSUSE Tumbleweed安装中几乎通过任何其他应用程序生成的文件对话框看上去都与打开文件对话框相同,而tkinter却产生了局促且难以理解的内容,并且使用了不熟悉的侧滚动界面。

I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:

https://stackoverflow.com/a/9319832

The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.


是否有适用于Python的可视分析器?[关闭]

问题:是否有适用于Python的可视分析器?[关闭]

我现在使用cProfile,但是我发现编写pstats代码来查询统计数据很繁琐。

我正在寻找一个视觉工具,向我展示Python代码在CPU时间和内存分配方面的工作。

Java世界中的一些示例是visualvmJProfiler

  • 是否存在这样的东西?
  • 是否有执行此操作的IDE?
  • dtrace的帮助吗?

我知道Linux版KCachegrind,但是我希望我可以在Windows / Mac上运行而无需安装KDE。

I use cProfile now but I find it tedious to write pstats code just to query the statistics data.

I’m looking for a visual tool that shows me what my Python code is doing in terms of CPU time and memory allocation.

Some examples from the Java world are visualvm and JProfiler.

  • Does something like this exist?
  • Is there an IDE that does this?
  • Would dtrace help?

I know about KCachegrind for Linux, but I would prefer something that I can run on Windows/Mac without installing KDE.


回答 0

我和一个朋友编写了一个名为SnakeViz的Python配置文件查看器,该查看器在网络浏览器中运行。如果您已经成功使用RunSnakeRun,则 SnakeViz可能不会添加那么多的值,但是SnakeViz的安装要容易得多。

编辑:SnakeViz支持Python 2和3,并且可以在所有主要系统上使用。

A friend and I have written a Python profile viewer called SnakeViz that runs in a web browser. If you are already successfully using RunSnakeRun SnakeViz may not add that much value, but SnakeViz is much easier to install.

Edit: SnakeViz supports Python 2 and 3 and works on all major systems.


回答 1

我只知道RunSnakeRun

前段时间也有关于PyDev(Eclipse)中的集成探查器的讨论,但是我不知道这是否会成为现实。

更新:不幸的是,似乎不再维护RunSnakeRun,并且它不支持Python 3。

I’m only aware of RunSnakeRun.

There was also some talk some time ago about an integrated profiler in PyDev (Eclipse), but I don’t know if that will ever see the light of day.

Update: Unfortunately it seems that RunSnakeRun is no longer maintained, and it does not support Python 3.


回答 2

我使用gprof2dot.py。结果看起来像这样。我使用这些命令:

  python -m cProfile -o profile.dat my_program.py
  gprof2dot.py -f pstats profile.dat | dot -Tpng -o profile.png

您需要安装graphvizgprof2dot.py。您可能需要一个方便的Shell脚本

I use gprof2dot.py. The result looks like this. I use those commands:

  python -m cProfile -o profile.dat my_program.py
  gprof2dot.py -f pstats profile.dat | dot -Tpng -o profile.png

You need graphviz and gprof2dot.py installed. You might like a convenience shell script.


回答 3

Spyder还为cProfile提供了一个非常不错的GUI:

Spyder also provides a pretty nice gui for cProfile:


回答 4

适用于Visual Studio的Python工具包含一个做得很好的图形分析器:http : //www.youtube.com/watch?v= VCx7rlPyEzE&hd =1

http://pytools.codeplex.com/

Python Tools for Visual Studio contains a very well done graphical profiler: http://www.youtube.com/watch?v=VCx7rlPyEzE&hd=1

http://pytools.codeplex.com/


回答 5

此人创造了一个图形化的配置文件,描述在这里。也许您可以将其用作自己工作的起点。

This person created a graphical profile, described here. Maybe you could use that as a starting point for your own work.


回答 6

KCacheGrind包含一个称为QCacheGrind的版本,该版本可在Mac OS XWindows上运行。

KCacheGrind includes a version called QCacheGrind which does run on Mac OS X and on Windows.


回答 7

试用Snakeviz。非常容易安装(通过pip),并且基于浏览器。

https://jiffyclub.github.io/snakeviz/

Try out Snakeviz. Very easy to install (via pip) and it’s browser based.

https://jiffyclub.github.io/snakeviz/


回答 8

Python Call Graph生成的图片与maxy’s answer中的图片非常相似。它还显示每个功能的总时间,由于某种原因,它没有反映在示例图中。

Python Call Graph generates pics very similar to those in maxy’s answer. It also shows total time for each function, for some reason it’s not reflected in the example graphs.


回答 9

我已经编写了一个基于浏览器的可视化工具profile_eye,它可以对gprof2dot的输出进行操作

gprof2dot非常擅长处理许多分析工具的输出,并且在图形元素放置方面做得很好。最终渲染是静态图形,通常非常混乱。

使用d3.js,可以通过未聚焦的元素,工具提示和鱼眼失真的相对淡入来消除很多杂乱

为了进行比较,请参阅profile_eye对gprof2dot使用规范示例的可视化。特别是对于Python,请参见cProfile输出示例

I’ve written a browser-based visualization tool, profile_eye, which operates on the output of gprof2dot.

gprof2dot is great at grokking many profiling-tool outputs, and does a great job at graph-element placement. The final rendering is a static graphic, which is often very cluttered.

Using d3.js it’s possible to remove much of that clutter, through relative fading of unfocused elements, tooltips, and a fisheye distortion.

For comparison, see profile_eye’s visualization of the canonical example used by gprof2dot. For Python in particular, see a cProfile output example.


回答 10

考虑pyflame +火焰图

Pyflame:适用于Python + Flamegraph的跟踪分析器

https://github.com/uber/pyflame

您可以使用pyflame跟踪正在运行的python进程。

Consider pyflame + flamegraph

Pyflame: A Ptracing Profiler For Python + flamegraph

https://github.com/uber/pyflame

You can trace towards a running python process using pyflame.


回答 11

我曾经使用过plop,发现它非常轻巧。快速了解性能。

I have used plop and found it to be very light-weight. Gives a quick insight into the perf.


如何使用Python创建可直接执行的跨平台GUI应用程序?

问题:如何使用Python创建可直接执行的跨平台GUI应用程序?

Python可在多种平台上工作,并且可用于桌面和Web应用程序,因此,我得出结论,有一种方法可以将其编译为Mac,Windows和Linux的可执行文件。

问题是我不知道从哪里开始或如何用它编写GUI,请问有人可以向我指出正确的方向吗?

Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.

The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?


回答 0

首先,您将需要一些具有Python绑定的GUI库,然后(如果需要)一些程序,它将Python脚本转换为独立的可执行文件。

具有Python绑定的跨平台GUI库(Windows,Linux,Mac)

当然,有很多,但是我在野外看到的最受欢迎的是:

完整列表位于http://wiki.python.org/moin/GuiProgramming

单个可执行文件(所有平台)

  • PyInstaller-最活跃的(也可以与一起使用PyQt
  • fbs-如果您在上方选择了Qt

单个可执行文件(Windows)

单个可执行文件(Linux)

  • 冻结 -与py2exe相同,但以Linux平台为目标

单个可执行文件(Mac)

  • py2app-再次像py2exe一样工作,但以Mac OS为目标

First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.

Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)

Of course, there are many, but the most popular that I’ve seen in wild are:

Complete list is at http://wiki.python.org/moin/GuiProgramming

Single executable (all platforms)

  • PyInstaller – the most active(Could also be used with PyQt)
  • fbs – if you chose Qt above

Single executable (Windows)

  • py2exe – used to be the most popular

Single executable (Linux)

  • Freeze – works the same way like py2exe but targets Linux platform

Single executable (Mac)

  • py2app – again, works like py2exe but targets Mac OS

回答 1

另一个系统(尚未在接受的答案中提及)是PyInstaller,该系统在py2exe无法使用时可用于我的PyQt项目。我发现它更易于使用。

http://www.pyinstaller.org/

Pyinstaller基于Gordon McMillan的Python Installer。不再可用。

Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use.

http://www.pyinstaller.org/

Pyinstaller is based on Gordon McMillan’s Python Installer. Which is no longer available.


回答 2

pyfree.py是py2exe的替代工具,它可以为Windows和Linux生成可执行文件。它比py2exe更新,并且可以很好地处理鸡蛋。我发现它无需配置即可针对多种应用程序神奇地工作得更好。

An alternative tool to py2exe is bbfreeze which generates executables for windows and linux. It’s newer than py2exe and handles eggs quite well. I’ve found it magically works better without configuration for a wide variety of applications.


回答 3

还有PyGTK,它基本上是Gnome Toolkit的Python包装器。我发现比起Tkinter来,我的想法更容易缠起来,这是因为以前几乎没有GUI编程知识。它工作得很好,并且有一些很好的教程。不幸的是,目前还没有适用于Windows的Python 2.6安装程序,并且可能有一段时间没有安装。

There’s also PyGTK, which is basically a Python wrapper for the Gnome Toolkit. I’ve found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn’t an installer for Python 2.6 for Windows yet, and may not be for a while.


回答 4

由于默认情况下现在几乎在所有非Windows操作系统上都安装了python,因此您真正需要确保的唯一事情就是已安装了您使用的所有非标准库。

话虽如此,有可能构建包括python解释器和您使用的任何库的可执行文件。但是,这可能会创建一个大型可执行文件。

MacOS X甚至在Xcode IDE中提供了对创建完整独立GUI应用程序的支持。这些可以由运行OS X的任何用户运行。

Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.

Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.

MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.


回答 5

对于GUI本身:

PyQT几乎是参考。

开发快速用户界面的另一种方法是编写一个Web应用程序,使其在本地运行并在浏览器中显示该应用程序。

另外,如果您选择lubos hasko建议的Tkinter选项,则可能要尝试Portablepy使您的应用程序在Windows环境下运行而无需使用Python。

For the GUI itself:

PyQT is pretty much the reference.

Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.

Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.


回答 6

我不确定这是否是最好的方法,但是当我在Windows上部署Ruby GUI应用程序(不是Python,但就.exe而言具有相同的“问题”)时,我只写了一个C#中的短启动程序,它调用我的主脚本。它编译为可执行文件,然后有一个应用程序可执行文件。

I’m not sure that this is the best way to do it, but when I’m deploying Ruby GUI apps (not Python, but has the same “problem” as far as .exe’s are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.


回答 7

# I'd use tkinter for python 3

import tkinter

tk = tkinter.Tk()
tk.geometry("400x300+500+300")
l = Label(tk,text="")
l.pack()
e = Entry(tk)
e.pack()

def click():
    e['text'] = 'You clicked the button'

b = Button(tk,text="Click me",command=click)
b.pack()

tk.mainloop()

# After this I would you py2exe
# search for the use of this module on stakoverflow
# otherwise I could edit this to let you know how to do it

py2exe

然后,您应该使用py2exe,例如,将运行该应用程序所需的所有文件都放入一个文件夹中,即使用户的计算机上没有python(我在说的是Windows …对于Apple os来说也没有必要我认为,由于可执行文件带有python,因此无需安装它。

建立这个档案

1)创建一个setup.py

使用此代码:

from distutils.core import setup
import py2exe

setup(console=['l4h.py'])

将其保存在文件夹中

2)将您的程序放在setup.py的同一文件夹中,在该文件夹中放入要使其可分发的程序:es:l4h.py

ps:更改文件名(从l4h更改为您想要的任何名称,这是一个示例)

3)从该文件夹运行cmd(在该文件夹上,右键单击+ Shift并在此处选择启动cmd)
4)在cmd:> python setup.py py2exe中编写
5)在dist文件夹中,您需要所有文件
6)您可以压缩并分发

py安装程序

从cmd安装

**

点安装pyinstaller

**

从文件所在的文件夹中的cmd运行它

**

pyinstaller file.py

**

# I'd use tkinter for python 3

import tkinter

tk = tkinter.Tk()
tk.geometry("400x300+500+300")
l = Label(tk,text="")
l.pack()
e = Entry(tk)
e.pack()

def click():
    e['text'] = 'You clicked the button'

b = Button(tk,text="Click me",command=click)
b.pack()

tk.mainloop()

# After this I would you py2exe
# search for the use of this module on stakoverflow
# otherwise I could edit this to let you know how to do it

py2exe

Then you should use py2exe, for example, to bring in one folder all the files needed to run the app, even if the user has not python on his pc (I am talking of windows… for the apple os there is no need of an executable file, I think, as it come with python in it without any need of installing it.

Create this file

1) Create a setup.py

with this code:

from distutils.core import setup
import py2exe

setup(console=['l4h.py'])

save it in a folder

2) Put your program in the same folder of setup.py put in this folder the program you want to make it distribuitable: es: l4h.py

ps: change the name of the file (from l4h to anything you want, that is an example)

3) Run cmd from that folder (on the folder, right click + shift and choose start cmd here)
4) write in cmd:>python setup.py py2exe
5) in the dist folder there are all the files you need
6) you can zip it and distribute it

Pyinstaller

Install it from cmd

**

pip install pyinstaller

**

Run it from the cmd from the folder where the file is

**

pyinstaller file.py

**


回答 8

PySimpleGUI包装了tkinter并在Python 3和2.7上运行。它还可以在Qt,WxPython和Web浏览器中运行,并且所有平台都使用相同的源代码。

您可以创建自定义GUI,以利用在tkinter中找到的所有相同窗口小部件(滑块,复选框,单选按钮等)。该代码往往非常紧凑和可读。

#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg

layout = [[ sg.Text('My Window') ],
          [ sg.Button('OK')]]

window = sg.Window('My window').Layout(layout)
button, value = window.Read()

PySimpleGUI文档中所述,要生成.EXE文件,请运行:

pyinstaller -wF MyGUIProgram.py

PySimpleGUI wraps tkinter and works on Python 3 and 2.7. It also runs on Qt, WxPython and in a web browser, using the same source code for all platforms.

You can make custom GUIs that utilize all of the same widgets that you find in tkinter (sliders, checkboxes, radio buttons, …). The code tends to be very compact and readable.

#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg

layout = [[ sg.Text('My Window') ],
          [ sg.Button('OK')]]

window = sg.Window('My window').Layout(layout)
button, value = window.Read()

As explained in the PySimpleGUI Documentation, to build the .EXE file you run:

pyinstaller -wF MyGUIProgram.py


回答 9

您不需要编译为Mac / Windows / Linux python。它是一种解释语言,因此您只需要在您选择的系统上安装Python解释器即可(这三个平台都可用)。

至于可以跨平台工作的GUI库,Python的Tk / Tcl小部件库可以很好地工作,我相信跨平台就足够了。

Tkinter是Tk / Tcl的python接口

从python项目网页:

Tkinter不是唯一的Python GuiProgramming工具包。但是,它是最常用的一种,并且几乎是唯一可以在Unix,Mac和Windows之间移植的一种

You don’t need to compile python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).

As for a GUI library that works cross platform, Python’s Tk/Tcl widget library works very well, and I believe is sufficiently cross platform.

Tkinter is the python interface to Tk/Tcl

From the python project webpage:

Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one, and almost the only one that is portable between Unix, Mac and Windows


回答 10

您可以appJar用于基本的GUI开发。

from appJar import gui

num=1

def myfcn(btnName):   
    global num
    num +=1
    win.setLabel("mylabel", num)

win = gui('Test')

win.addButtons(["Set"],  [myfcn])
win.addLabel("mylabel", "Press the Button")

win.go()

请参阅appJar网站上的文档

pip install appjar通过命令行进行安装。

You can use appJar for basic GUI development.

from appJar import gui

num=1

def myfcn(btnName):   
    global num
    num +=1
    win.setLabel("mylabel", num)

win = gui('Test')

win.addButtons(["Set"],  [myfcn])
win.addLabel("mylabel", "Press the Button")

win.go()

See documentation at appJar site.

Installation is made with pip install appjar from command line.


回答 11

!!! KIVY !!!

看到没有人提到Kivy,我感到非常惊讶!!!

我曾经使用Tkinter进行过一个项目,尽管他们确实提倡它有很多改进,但仍然给我Windows 98的感觉,所以我改用Kivy

我一直在关注一个教程系列如果有帮助, …

只是为了了解一下奇异果的外观,请看以下内容(我正在从事的项目):

而且我现在差不多已经工作了一个星期了!您问Kivy有什么好处?检查一下一下

我之所以选择它,是因为它的外观以及它也可以在移动设备中使用。

!!! KIVY !!!

I was amazed seeing that no one mentioned Kivy!!!

I have once done a project using Tkinter, although they do advocate that it has improved a lot, it still gives me a feel of windows 98, so I switched to Kivy.

I have been following a tutorial series if it helps…

Just to give an idea of how kivy looks, see this (The project I am working on):

And I have been working on it for barely a week now ! The benefits for Kivy you ask? Check this

The reason why I chose this is, its look and that it can be used in mobile as well.