Script works in IDLE, but .py-file doesn't wor

2019-02-07 01:55发布

I have a tkinter script, which runs just fine in IDLE. However, when I double click the .py-file from Windows Explorer, the console window flashes half a second and then it exits.

I was able to screenprint the console window. It says:

...etc.etc...
NameError: global name 'simpledialog' is not defined

simpledialog is a module in tkinter which I use in my script. As I do from tkinter import *, there is no need to explicitly write tkinter.simpledialog.

It works in IDLE, why not as .py?

5条回答
SAY GOODBYE
2楼-- · 2019-02-07 02:00

I had exactly the same problem with one of my scripts utilizing Tkinter. Adding call to mainloop() fixed the issue. See this tutorial for an example: [http://sebsauvage.net/python/gui/#import1

In my case, in the init function I have

def __init__(self,Width=400, Height=400):
        # Create GUI window ------------------------------            
        win = Tk()
        ...

in the end of init I added:

        win.mainloop()

Now it works by just running the file. Hope this helps

查看更多
来,给爷笑一个
3楼-- · 2019-02-07 02:05

Similar trouble for me just now, in my first week with python. But I dimly remembered a similar problem with a simple early test script and thought the trouble then was # comments. So I tried that with my Tkinter infused .py script. It ran fine in IDLE as you say, then only flashed when clicked in windows. But there were a couple # commented lines at the top of file.

I took them all out and it now runs no sweat directly in windows. Have a look .. for #.

Sorry, can't seem to delete this post. Now the files work #comments included. Don't know what's up with that. ..

查看更多
Melony?
4楼-- · 2019-02-07 02:15

IDLE uses Tkinter as its graphical environment. It is possible that your code is relying on a side effect of an import by IDLE itself. This is especially true if you use IDLE without a subprocess.

The simpledialog module does not import when using from tkinter import *. Try adding this to your code:

import tkinter.simpledialog as simpledialog
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-07 02:18

Have you updated your PATH environment variable so that your Python executable is found? You can find more information on how to do here - Using Python on Windows

But you basically need to make sure that the folder containing python.exe (e.g. C:\Python32) is displayed when you type the following command from a prompt:

echo %PATH%
查看更多
Evening l夕情丶
6楼-- · 2019-02-07 02:19

I found that changing the executable py file to a file.pyw fixed the problem. This tells python to execute it using the pythonw.exe which runs the script without the terminal/console in the background.

Not sure why this works, perhaps some screwed up environment variables from a previous python installation.

查看更多
登录 后发表回答