Tkinter: NameError: name 'tk' is not defined - user-interface

I have been following tutorials of how to create a graphical user interface (GUI), in order to get used to it because I will use it in the future. The majority of tutorials use these commands at the first lines:
from tkinter import *
root = tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
If I run this simple code I get the following error:
File
"C:/Users/Gerard/Dropbox/Master_Thesis_Gerard_Pujol/Python_Tryouts/creting_simpleGUI.py", line 11, in
root=tk()
NameError: name 'tk' is not defined
After that I changed my code, so I used something like that:
import tkinter as tk
root = tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
Now, the error is the following:
"C:/Users/Gerard/Dropbox/Master_Thesis_Gerard_Pujol/Python_Tryouts/creting_simpleGUI.py", line 11, in
root=tk()
TypeError: 'module' object is not callable
Do you know what's going wrong? Could you help me please?
I'm using Spyder for Python 3.3, but I suppose it isn't a problem.

The tutorials you've seen is probably for Python 2. In Python 3 they've changed the naming conventions. So instead of root = tk() in P2, it's root = Tk() in P3 (Tk() is a class, hence the capital T).
In your second example your should write root = tk.Tk() after the import statement

I've just had a similar problem which I found out was because my Python console window in Spyder was connected to a different .py file that I was working on earlier so I closed it and opened a new python console in Spyder and the problem was gone.

Related

ModuleNotFoundError seen after the first time a job is run on a Ray cluster

I'm running a script which imports a module from a file in the same directory. The first time I run the script after starting the cluster the script runs as expected. Any subsequent times I run the script I get the following error: ModuleNotFoundError: No module named 'ex_cls'
How do I get Ray to recognize modules I'm importing after the first run?
I am using Ray 1.11.0 on a redhat Linux cluster.
Here are my scripts. Both are located in the /home/ray_experiment directory:
--ex_main.py
import sys
sys.path.insert(0, '/home/ray_experiment')
from ex_cls import monitor_wrapper
import ray
ray.init(address='auto')
from ray.util.multiprocessing import Pool
def main():
pdu_infos = range(10)
with Pool() as pool:
results = pool.map(monitor_wrapper, [pdu for pdu in pdu_infos])
for pdu_info, result in zip(pdu_infos, results):
print(pdu_info, result)
if __name__ == "__main__":
main()
--ex_cls.py
import sys
from time import time, sleep
from random import randint
import collections
sys.path.insert(0, '/home/ray_experiment')
MonitorResult = collections.namedtuple('MonitorResult', 'key task_time')
def monitor_wrapper(args):
start = time()
rando = randint(0, 200)
lst = []
for i in range(10000 * rando):
lst.append(i)
pause = 1
sleep(pause)
return MonitorResult(args, time() - start)
-- Edit
I've found that by adding these two environment variables I no longer see the ModuleNotFoundError.
export PYTHONPATH="${PYTHONPATH}:/home/ray_experiment/"
export RAY_RUNTIME_ENV_WORKING_DIR_CACHE_SIZE_GB=0
Is there another solution that doesn't require disabling the working environment caching?
The issue here is that Ray's worker processes may be run from different working directories than your driver python script. In fact, on a cluster, they may even be run from different machines. This is coupled by the fact that python looks for the module based on a relative path (to be precise, cloudpickle serializes definitions in other modules by reference).
The "intended" solution to this problem is to use runtime environments.
In particular, you should do ray.init(address='auto', runtime_env={"working_dir": "./"}) when starting Ray to ensure that the module is passed to other processes.
After searching for similar error I found this in Ray docs:
https://docs.ray.io/en/latest/ray-core/handling-dependencies.html#library-development
Adding __init__.py to root of these directories and handing them over with this kwarg solved my issue with ModuleNotFoundError. Another part of solution is to install all requirements to the container the ray is running in and probably starting it in same workdir as app (or passing workdir in runtime kwargs)
To answer OPs problem I would try something like this:
import ex_cls
# it cannot pass classes, just whole module
ray.init(address='auto', runtime_env={"py_modules": [ex_cls]})

NameError: name 'rotor' is not defined

I try to import and run selfmade modules under Spyder.
The main.py programm
import rot
f=rotor(b_x,b_y,b_z,x,y,z)
The rot.py programm
def rotor(bx,by,bz,x,y,z):
import numpy as np
...
The issue is:
File "C:\Users\Professional.spyder-py3\my_pro\jgut\main.py", line 93, in
f=rotor(b_x,b_y,b_z,x,y,z)
NameError: name 'rotor' is not defined
Problem doesn't disappear even after starting brut force start of any imported modules.
Is there a way to start all imported modules simultaniously? Or maybesomeone faced this problem?
P.S. Problem appeared today after Anaconda reinstall, becouse of incopatebilities with IK-Multimedia apps (I just removed them). I was starting all the mudules by brut force from the begining.
1) Please, do not import modules in functions!
2) rotor is not defined because it is in the rot namespace. You can call it by rot.rotor(args). If you wanted to do call it the way you do, you have to import it like this: from rot import rotor or from rot import * (which imports everything from the rot module and is a bad practise - you should only import what you need).
The error has nothing to do with anything written in the last 2 paragraphs.

Writing out document in GUI executable using cx_freeze not working

I made an executable gui (with tkinter) file using cx_freeze. The executable has several buttons. When the user click the button, the calculation should work and then it will write out an xlsx file.
Everything went good when I make the executable, there was no error. But when I click the button, it seems like the calculation works (since it was loading), but then it does not write out the xlsx file.
I don't know what went wrong. Anyone can help me?
Here's the setup.py file:
import sys
from cx_Freeze import setup, Executable
import os
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [Executable("gui.py", base=base)]
packages = ["tkinter", 'xlsxwriter', 'matplotlib']
options = {
'build_exe': {
'includes': ["os", "tkinter", 'numpy.core._methods', 'numpy.lib.format', 'xlrd', 'scipy', 'pandas'],
'include_files': [r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tcl86t.dll",
r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tk86t.dll"]
},
}
os.environ['TCL_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name="Tool",
version="1.0",
description="Tool prototype for calculating",
options=options,
executables=executables
)
I've solved the problem.
What i did was to change the base in setup.py to : base = None
and I installed the xlsxwriter by following this thread: ImportError: No module named 'xlsxwriter': Error in bamboo
After this, I encountered another problem:
No module named: scipy.sparse.csgraph._validation
but I simply add this to the 'includes': ['scipy.sparse.csgraph._validation', ...]
now everything works perfectly.
I hope this helps anyone who has the same problem.

AttributeError: 'module' object has no attribute 'testmod' Python doctest

When ever I try to doctest in python, basically whenever I run the code
if __name__ =="__main__":
import doctest
doctest.testmod()
I get this response from the interpreter
AttributeError: 'module' object has no attribute 'testmod'
I can run this code just fine, but whenever I run it on my windows machine, it doesn't work.
My machine is running Windows theirs is OS X, but are running python 2.7.5.
Thank you :)
Make sure that you are not trying to save your test file as doctest.py. The print statement suggested above will show it. If the file name is doctest.py, then rename it and try again.
AttributeError: 'module' object has no attribute 'testmod'
Clearly stats that the doctest module you're importing do not has the testmod() method.
Possible reasons can be:
You have more than one doctest modules in the lib.
and, it is the other one (without the testmod() method) which is getting imported as result of import doctest.
Solution: Look for the path of standard doctest module.
if __name__ =="__main__":
import doctest
if doctest.__file__ == "/path/to/standard/doctest-module":
doctest.testmod()
It looks like there is a different module called doctest that is being imported instead of the standard one.
To find out which module is being imported exactly, simply add the following print:
if __name__ =="__main__":
import doctest
print doctest.__file__ # add this
doctest.testmod()
The print should produce something similar to C:\Python27\lib\doctest.pyc, depending on the location and version of Python you're using. Any other output means you are importing the wrong module, and explain why you're getting the error.

Embedded Python loads module but does not load that module's internal import statements

At long last(!) I've compiled Boost::Python and have gotten my XCode project to import a local module. This module starts with the line from xml.dom import minidom, but when it executes, I'm given this error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "FeedStore.py", line 1, in <module>
from xml.dom import minidom
ImportError: No module named xml.dom
However, I know that I've installed the xml Python module -- when I open Python from my command prompt and type from xml.dom import minidom, everything goes smoothly. Moreover, when I import the module, it behaves as I would expect.
I suspected that there was something wrong with sys.path, so I compared the one I get from the prompt to the one that's being used in my embedded module. The only difference is that the embedded sys.path does not include ''. I've tried appending it, but that didn't change the behavior.
I also suspected that the embedded version was accessing a different version of Python than I was using from the prompt, but sys.prefix matched between both executions.
Here's the code that imports my module and runs it. It's pretty bare-bones at the moment (not even reference counting yet) because at this point I'd just like to make sure I'll be able to embed my module (I'm a total newbie C++ programmer).
Py_Initialize();
//PyRun_SimpleString("import sys");
//PyRun_SimpleString("sys.path.append('')"); //tried this to no avail!
PySys_SetPath("/Users/timoooo/Documents/Code/TestEmbed/"); //this allows me to import my local module
PyRun_SimpleString("import FeedStore as fs"); //here's where it whines about the lack of xml.dom
PyRun_SimpleString("store = fs.feedStore()");
PyRun_SimpleString("print store.next()");
Py_Finalize();
I'm probably misunderstanding something essential about boost::python. Can anyone help me out?
Despite having identical sys.path values, calling
PyRun_SimpleString("sys.path.append(\"<<path>>\")");
with the places I needed fixed the problem.

Resources